How to Exit from a Function in Javascript
By Henri Parviainen
How to exit from a Javascript function?
The question may seem a bit silly for experienced Javascript developers.
However, it's a solid question, especially if you are only just getting started with Javascript or web development in general.
Some other programming languages have specific exit methods which you could use to break out of a function. However, Javascript doesn't have an actual exit
method. How can you exit from function then?
Exit function by using return statement
Luckily, the answer to the question is quite simple. We can exit a Javascript function at any given time by using the return
statement.
Are you familiar with the return statement already? You might have written functions that return a value, maybe a string, or some other type. Well, if we want to break out from a function, we can use the return statement by itself which will return undefined
.
It's especially useful when you have a function with multiple possible outcomes. Maybe there is one specific case if a certain condition gets fulfilled where you need to stop and break out of the function and not return anything.
// We can exit a function by using the return statement. This will actually return 'undefined'.
const yourFunction = (condition) => {
if (condition) {
return;
}
...
};
console.log(yourFunction(true));
// returns undefined
Exit a function by returning false
Another option to exit a function is to simply return false.
/// We could also just return false if we want to break out of a function
const yourFunction = (condition) => {
if (condition) {
return false;
}
...
};
console.log(yourFunction(true))
// returns false