Javascript function return


The JavaScript function's return statement is used to specify the value returned from the function. When a function to executed, to get a run results, you need to use the return statement to return the results.

The following example returns the sum of two parameter values:

function sum(x,y) {
   return x + y;
}
result = sum(2, 3);
document.write(result);
Output
5

Similar to Java, PHP and other languages ​with function implementation. The return statement stop the code immediately, code after return statement will be ignored, for example :

function sum(x, y) {
   return x + y;
   document.write("Text");
}

In the above example, document.write ("prompt text"); statement will never be executed.


A return statement with no return value

If the function has no return value, you can exit the function at any time by calling the return operator with no arguments:

function sum(x, y){
   if (x < y) {
      return;	
   } else {
      return x - y;
   }
}

If the function has no return value, or a return statement with no arguments is called, then the value it really returns is undefined .




Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook