What does “return;” mean in javascript?

前端 未结 1 1423
后悔当初
后悔当初 2020-12-10 20:50

Ran over this code:



        
相关标签:
1条回答
  • 2020-12-10 21:17

    The return statement in Javascript terminates a function. This code basically says that if !function1() (the opposite of function1()'s return value) is true or truthy, then just stop executing the funciton.

    Which is to say, terminate this function immediately. The semicolon is a statement terminator in javascript. If !function1() ends up being true or truthy, then the function will return and none of the code below it will be executed.

    Return can be used to return a value from a function, like:

    function returnFive(){
       return 5;
    }
    

    Or, like in this case, it's an easy way to stop a function if--for some reason--we no longer need to continue. Like:

    function isEven(number){
      /* If the input isn't a number, just return false immediately */
      if(typeof number !== 'number') return false;
       /* then you can do even/odd checking here */
    }
    

    As you suspected, this has nothing to do specifically with jQuery. The semicolon is there so that the Javascript engine knows that there are two statements:

    if(!function1()) return;
            function2();
    

    Not just one statement, which you can see would totally change the program:

    if(!function1()) return function2();
    
    0 讨论(0)
提交回复
热议问题