In this section we will learn what the return statement is and how to use it in JavaScript.
What is Return Function in JavaScript?
Functions are capable of returning values as their output when they are being called. These values can then be used in other operations like being stored in a variable or being sent to the browser’s console, etc.
Now in order to make a function to return a value, we use the return statement.
Note: you’ll see how to use the return statement in the rest of this section but just remember that the return keyword acts as the terminator of the function as well. This means no other statement after the return will be executed by the execution engine and they are simply ignored. So don’t put statements after the return because they won’t be executed.
How to Return Statement in JavaScript? (Return Statement Syntax)
In order to return a value from a function we use the return keyword.
Basically, all we need to do, is to put the value that we want to return as the result of calling a function on the right side of this keyword.
For example:
return 10;
return “John Doe”;
return true;
Example: creating return function in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<p class = "output">Output: </p>
<script type="text/javascript">
function sum(val1, val2){
let result = val1 + val2;
return result;
}
document.querySelector(".output").innerText = `The sum is: ${sum(4,5)}`;
</script>
</body>
</html>
Here the sum() function takes two arguments, adds them together and returns the final result using the return statement.
So because of this return statement, we got back a value from this sum() function.
Multiple Return Statements in JavaScript Function
In a function we can use multiple return statements as well. This is mainly useful when we have multiple conditions in a function (created by multiple if-else statements for example) and want to return from that function if any of those conditions met.
Let’s see this practice.
Example: creating multiple return statements in JavaScript function
<!DOCTYPE html>
<html>
<head>
<title>JavaScript is fun! :)</title>
</head>
<body>
<p class = "output">Output: </p>
<script type="text/javascript">
function age(val){
if (val >18){
return "You are above the legal age";
}else{
return "You're under legal age";
}
}
document.querySelector(".output").innerText = age(30);
</script>
</body>
</html>
Here we have the if statement as well as the else statement. Within the body of both statements we have the return statement.
Now, if the input value of this method is above 18, then the return statement of the if will be executed and the rest of source code in this function will be ignored.
Also if the input value of the age function is less than the value 18, then the body of the else statement will be executed and the return statement in that body will terminate the function and returns its value as the final result of the age() function.