Javascript Return Statement
The return statement in JavaScript is used to end the execution of a function and return a value to the caller. It is used to control function behaviour and optimise code execution.
function add(a, b) {
return a + b;
}
let sum = add(10, 20);
console.log(sum);//30
When to use return in js?
Use return inside a function when you want to send a value back to the place where the function was called.
1. To return a calculation result
function add(a, b) {
return a + b;
}
console.log(add(10, 20));
Output:
30
return adds the values and sends the result back.
2. To store a value
function square(num) {
return num * num;
}
let result = square(5);
console.log(result);
Output:
25
return sends 25 back and stores it in result.
3. To check a condition
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4));
Output:
true
return sends true or false back.
4. To stop a function
function test() {
console.log("Start");
return;
console.log("End");
}
test();
Output:
Start
After return, the function stops. "End" is not printed.return is used to control a function's behavior by deciding what value should be sent back based on conditions. It also optimizes code execution because once return is reached, the function stops executing any remaining statements.
5. To Use the Result in Another Operation
A returned value can be used in other calculations, conditions, or functions.
function add(a, b) {
return a + b;
}
let total = add(10, 20);
console.log(total * 2);
Output:
60
Here, return sends the value back, and that value is reused in another operation.
When return is not needed
function greet() {
console.log("Hello");
}
greet();
Output:
Hello
Here we only print a message. No value is sent back, so return is not required.
Without return
function add(a, b) {
a + b;
}
let sum = add(10, 20);
console.log(sum);
Output:
undefined
Since the function does not return a value, JavaScript automatically returns undefined
Simple Rule
Need to send a result back from a function? → Use return
Only displaying output? → return is not required
Use return when you want to:
✔ Get a result.
✔ Store a value.
✔ Check conditions.
✔ Stop a function.
✔ Use the result in another operation.
References
https://www.geeksforgeeks.org/javascript/javascript-return-statement/
Top comments (0)