简体   繁体   中英

How to run a code after a return statement in javascript

I encountered an issue while solving an algorithmic problem yesterday, which goes thus.

  remove() {
    // your code here
    if(!this.arr.length) {
      return -1;
    }
    else() {
     return this.arr[0];
     this.arr.splice(0, 1);
    }
  }

Note:- This is part of one of the class methods.

I wanted to get the item in the zero index before splicing that same item out. Then I realized that a code after a return statement is called an unreachable code and therefore, won't be executed.

In this particular case you can use the return value of splice : it returns the slice that was extracted, and so it contains the value you want to return.

As a side note, the else part does not need an if to test the array length, as that condition is guaranteed to be true.

  remove() {
    if(!this.arr.length) {
      return -1;
    }
    else {
     return this.arr.splice(0, 1)[0];
    }
  }

Note that for this particular splicing, there is a shortcut method: shift :

  remove() {
    if(!this.arr.length) {
      return -1;
    }
    else {
     return this.arr.shift();
    }
  }

You can shorten this with the conditional operator:

  remove() {
    return this.arr.length ? this.arr.shift() : -1;
  }

And if you are certain that your array will not have null or undefined entries, you can even do:

  remove() {
    return this.arr.shift() ?? -1;
  }

And so, I came over here for an answer and found a setTimeout solution that didn't really work for my code. So, I figured out a solution that goes thus.

  remove() {
    // your code here
    if(!this.arr.length) {
      return -1;
    }
    else() {
     let firstEl = this.arr[0];
     this.arr.splice(0, 1);
     return firstEl;
    }
  }

store what you wish to return in a variable, then execute your code afterward before returning the value you stored. In that way, it is hierarchical in some sense.

here is an old tricky solution.

let arr=[1,2,3,4,5]
 function remove() {
     try {
         // your code here
        if(!arr.length) {
          return -1;
        }
        else if(arr.length) {
         return arr[0];
       
        }
    } finally {
         arr.splice(0, 1);
    } 

  }
  console.log(remove());
  console.log(arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM