JavaScript, how to exit a function

By

Learn how to exit a JavaScript function early using the return keyword, which stops execution immediately and can hand back a value or an error object.

~~~

To exit a function in JavaScript, use the return keyword. Whenever JavaScript sees return, it immediately stops running the function, and any value you put after it is handed back to the caller.

If you put nothing after return, the caller gets undefined.

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.

Early returns keep code flat

This pattern is called a guard clause. You check the bad cases first, exit right away, and the rest of the function stays at one level of indentation.

Compare this:

function sendInvoice(customer) {
  if (customer) {
    if (customer.email) {
      // the actual work
    }
  }
}

with this:

function sendInvoice(customer) {
  if (!customer) return
  if (!customer.email) return

  // the actual work
}

The second version reads top to bottom. No nesting to keep in your head.

Returning an error to the caller

Sometimes exiting silently is not enough, and the caller needs to know what went wrong. 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).

throw is the other way out

If a missing parameter is a programming error rather than a normal case, throwing can be a better fit:

function calculateTotal(cart) {
  if (!cart) {
    throw new Error('cart is required')
  }

  // go on with the function
}

throw also exits the function immediately, but the caller has to handle it with try/catch, or the error propagates up.

Watch out for the newline trap

One pitfall: never put the returned value on the next line.

function getResult() {
  return
    { error: true }
}

getResult() //undefined

JavaScript’s automatic semicolon insertion turns that into return;, and the object below is never reached. The function returns undefined.

The fix is to keep the value, or at least its opening brace or parenthesis, on the same line as return.

~~~

Related posts about js: