JavaScript, how to exit a function
How to quickly end a JavaScript function, in the middle of it
Sometimes when you’re in the middle of a function, you want a quick way to exit.
You can do it using the return keyword.
Whenever JavaScript sees the return keyword, it immediately exits the function and any variable (or value) you pass after return will be returned back as a result.
This is something I use all the time to make sure I immediately exit a function if some condition is not as I expect it.
Maybe I expect a parameter and it’s not there:
function calculateSomething(param) {
if (!param) {
return
}
// go on with the function
}
If the param value is present, the function goes on as expected, otherwise it’s immediately stopped.
In this example I return an object that describes the error:
function calculateSomething(param) {
if (!param) {
return {
error: true,
message: 'Parameter needed'
}
}
// go on with the function
}
What you return depends on how the function is expected to work by the code that calls it.
Maybe you can return true if all is ok, and false in case of a problem. Or as I showed in the example above, an object with an error boolean flag, so you can check if the result contains this property (or a success: true property in case of success).
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.