Returning Values from Functions

Often, a function needs to return a value to the calling code. Adding a return keyword followed by a variable or value returns that value from the function. For example, the following code calls a function to format a string, assigns the value returned from the function to a variable, and then writes the value to the console:

function formatGreeting(name, city){
  var retStr = "";
  retStr += "Hello <b>" + name + "/n");
  retStr += "Welcome to " + city + "!";
return retStr;
}
var greeting = formatGreeting("Brad", "Rome");
console.log(greeting);

You can include more than one return statement in the function. When the function encounters a return statement, code execution of the function stops immediately. If the return statement contains a value to return, then that value is returned. The following example shows a function that tests the input and returns immediately if it is zero:

function myFunc(value){
  if (value == 0)
    return value;
  <code_to_execute_if_value_nonzero>
  return value;
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.169.212