The return
statement in JavaScript is used to end the execution of a function and return a value from that function.
Return in Functions
In functions, the return
statement ends the function execution and specifies a value to be returned to the function caller.
Here’s an example:
function add(a, b) {
return a + b;
}
let sum = add(5, 3); // sum will be 8
In this example, the add
function returns the sum of a
and b
. The returned value is then stored in the sum
variable.
Return Without a Value
If the return
statement is used without a value, the function will stop executing and return undefined
.
function greet() {
console.log('Hello, Junaid');
return;
}
let result = greet(); // result will be undefined
In this example, the greet
function does not return a value, so result
is undefined
.
Early Exit
The return
statement can also be used to stop the execution of a function early.
function isPositive(number) {
if (number < 0) {
return false;
}
// Some other code here...
return true;
}
In this example, if number
is less than 0
, the function returns false
immediately and the rest of the code is not executed.
The return
statement is a powerful tool in JavaScript. It controls the flow of a function and allows values to be passed from a function back to where it was called. Understanding how to use the return
statement effectively is crucial to writing good JavaScript code.