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 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook