Return statement to exit function prematurely
A return statement can also be used to exit the function prematurely in JavaScript in those cases where the condition is met.
Example: Using a return statement to early exit from the function based on certain conditions.
Javascript
function isDivisible(number) { if (number%2==0) { return true ; } return false ; } console.log(` Number is divisble by 2: ${isDivisible(107)}`) console.log(` Number is divisble by 2: ${isDivisible(24)}`) |
Number is divisble by 2: false Number is divisble by 2: true
How to use Return in JavaScript ?
JavaScript allows us to use the return statement to end the function’s execution to specify the value that needs to be returned to the code that is calling it. Below are the methods and examples of how to use a return statement in JavaScript.
Syntax:
function nameOfFunction()
{
return result // Value that need to be returned
}
Table of Content
- Simple return statement
- Return statement to return different types
- Return statement for returning objects
- Return statement to return a function
- Return statement to exit function prematurely