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).
I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025