Function Return

When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller".


This function calculates the product of two numbers, and returns the result:

  var x = myFunction(4, 3);  // Function is called, return value will end up in x

  function myFunction(a, b) {
    return a * b;   
// Function returns the product of a and b
}                 // Function is called, return value will end up in x

The result in x will be 12.

HTML file: Displayed by browser:
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
    return a * b;
}
   document.getElementById("demo").innerHTML = myFunction (4, 3);
</script>
</body>

This example calls a function which performs a calculation, and returns the result:

At first, I was confused about this one, because the "var x" part was not used in the html document at all. However, I did experiment and found that if I added "var x = myFunction(4, 3);" to the script and used "document.getElementById("demo").innerHTML = x;" then I would get the exact same results from the browser.

BackTable of ContentsNext