How to use return statement in JavaScript
In functions, we can return the value of the function by using the keyword “RETURN”. When we use the return statement in a function it’s the execution of the entire function. Which means the other code that is written after the return statement is not going to work.
Example:
function sum(num1, num2) {
return num1 + num2;
}
let result = sum(1, 2);
console.log(result); // 3
As you can see in this example we created a function called “sum” with two parameters and we have given the two arguments at the end when we called the function. Here we have returned the total sum of num1 and num2 by using the return keyword. And that’s how when we called the sum function — the returned value of 1 and 2 would result in 3.Then stored the returned value into the result variable. When we log the result variable the result would be the total sum of 1 and 2 which is 3. And that’s how we gain the returned value by using the return statement in a function.
We can actually return values of any data types:
Example:
function getPerson(name, age) {
return {name: name, age: age }
}
let person = getPerson(“John”, 21);
console.log(person); // { name: “John” , age : 21 }
So here we have returned the value of getPerson() arguments’ name and age by putting the value into {} as an object formation. As you can see when we log the result would be like this {name:John,age:21}.As we have mentioned before, code that is written after the return statement won’t work.
Example:
function minus(num1, num2) {
return;
num1 — num2;
}
let result = minus(4, 2);
console.log(result); // undefined
In this example, the final result is showing undefined. Look at the code closely, there is a semicolon (;) after the return statement and it’s not clearly showing what the function is trying to return. And the code below the return statement is not working. Hen forth, it’s showing undefined.
That’s why sometimes we can put the () parenthesis right after the return statement. Like this:
Example
return( 1+2);
When we put () parenthesis like the above example: the return statement would return the entire value that is inside the parenthesis.
We mostly use this kind of parenthesis return when we want to return HTML elements, arrays, and objects.
Example
function addElement(){return( “<h1>There is no data yet!</h1>”);}
Hence, the return statement is the execution of a function.
When we use the return in a function it would only work when we put some value after the return keyword. If not, it’s going to result as undefined. When we return some value inside the ()parenthesis, it would execute the entire value that is inside the parenthesis.