Returning a value from a function

To return a value from a function, use the return command along with a variable or value at the end of the function's command block. Consider the following function definition:

function isEven (num) {
if (num % 2 == 0) {
return num;
}
}

This function determines if a number is even. This function takes one parameter, num. On line 4, we return the value of num. Note line 4 is only executed if the Boolean expression on line 3 is true. Note that our Boolean expression uses the modulus operator. Let's find even numbers between 1 and 20 by using the function definition we show above.

In the following code,

<script language="javascript">
function isEven (num) {
if (num % 2 == 0) {
return num;
}
}
function printMessage (num) {
if (num > 1) {
document.write (num + " ");
}
}
var evenNum;
document.write ("Even numbers: ");
for (i = 1; i <= 20; i++)
{
evenNum = isEven (i);
printMessage (evenNum);
}
</script>

we are using two functions. We call the isEven () function on line 16 inside a for loop. Our for loop is on lines 14 through 18. The for loop executes 20 times and calls the isEven () function and the printMessage () function 20 times. The first time the isEven function is called with the parameter value 1. The function returns nothing because 1 % 2 does not equal 0, so the printMessage () function will print nothing. However, when the second time the for loop is run, the value 2 is passed to the isEven () function. This is a even number because 2 % 2 is 0 so the function will return 2. In this case, the printMessage () function will print the number 2. The following shows the output of the JavaScript code: