3. Using the return statement
Say for example that you want to use the sum from our first function example for another function or
in another operation in the main function. To do this, the value of the output must be passed to outside of the
function and a variable outside the function must be declared to store the value being passed from the
function. Look at the code below:
<script>
function getSum(a, b){
sum = a + b;
return sum;
}
x = getSum(1,2);
</script>
The return keyword instructs the function to pass the value of sum to outside of the function and
return to where the function is called. In the case of the code above, the function will return to the variable x.
It is also in variable x that the function output will be stored. You can then process or do operations on the
variable x afterwards in the main function of your JavaScript code.
The example above shows that return statements are used to pass values from inside a function to a
variable outside the function. This is not the only use of return though. Return statements are also used as
break statements to end the execution of functions or loops before all lines inside the function or loop are
executed. The example below shows how a return statement is used in this case. Let’s say that you need to
prompt a user to input a non-numeric character. The loop will continue to ask the user for an input until the
correct input is provided.
<p id="demo"></p>
<script>
function myFunction() {
while (true){
var number = prompt("Please a letter");
if (isNaN(number)) { /* note: the isNaN() test whether the value in number is Not a Number and returns true otherwise it returns false. */
document.getElementById("demo").innerHTML ="It is a letter!";
return false;
}
}
}
myFunction();
</script>
Aside from using two methods above, you can also directly print the output by calling the function
from the print statement. Look at the code below as an example:
Aside from the printing statement, you can also directly call the function from an operation, instead of using a temporary variable first and then using that variable for an operation.