Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "return;" mean in javascript?

Ran over this code:

if(!function1()) return;
function2();
function3(array1[index1]);

What does having an instant semicolon after return mean? I found it under a jquery code. jquery has nothing to do with it right?

like image 789
typescript Avatar asked Mar 26 '15 23:03

typescript


People also ask

What is return in JavaScript?

The return statement stops the execution of a function and returns a value.

What does the return value do in JavaScript?

The return statement ends function execution and specifies a value to be returned to the function caller.

When would you use return in JavaScript?

There are two times you'll want to return in a function: When you literally want to return a value. When you just want the function to stop running.

What is return used for?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function. For more information, see Return type.


1 Answers

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();
like image 147
Aweary Avatar answered Sep 24 '22 19:09

Aweary