Skip to content

JavaScript, how to exit a function

New Course Coming Soon:

Get Really Good at Git

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).

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: