Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

syntax - What does "return;" mean in javascript?

Ran over this code:

if(!function1()) return;
function2();
function3(array1[index1]);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...