Function Return Values

Function Return Values

In Javascript functions you can return a value by using the return keyword. Return is optional in functions, so if you need to send result of your calculation or need to return any value from a function, you would use the return keyword.

In the following example, I have a function named Addition which accepts two values and then returns the result of adding the two values. After the function ends, I declare two variables with values 12 and 8. Then I call the Addition function by passing the two variables I created. The result of the function is passed to result variable and then the result value is printed.

function Addition(value1, value2) {
    return value1 + value2;
} 
let val1 = 12;
let val2 = 8;
let result = Addition (val1,val2);
document.write(result);

The above example will have the below output:

20

Return Stops Execution

Once a function reaches the return statement, the rest of the code in function will not execute.

In the below example, Addition function returns the value on it's second line. The third line of the function will not execute.

function Addition(value1, value2) {
    document.writeln("Calculating.......");
    return value1 + value2
    document.writeln("Done");
} 
let val1 = 12;
let val2 = 8;
let result = Addition (val1,val2);
document.writeln(result);

The above example will have the below output:

Calculating....... 20

Other Notes

If a function does not return anything, but you assign the function call to a variable; then the variable will have the value undefined

function Addition(value1, value2) {
    document.writeln(value1 + value2);
} 
let val1 = 12;
let val2 = 8;
let result = Addition (val1,val2);
document.writeln(result);

The above example will have the below output:

20 undefined