JavaScript, how to exit the function

How to quickly end JavaScript functions in the middle

Sometimes, when you are in the middle of a function, you want a quick exit method.

you can use itreturnKey words.

Whenever JavaScript seesreturnKeyword, it will exit the function immediately, and any variable (or value) passed after the return will be returned as the result.

This is something I have been using to make sure that in certain situations that are not what I expect, I immediately exit the function.

Maybe I expect a parameter, but it doesn't exist:

function calculateSomething(param) {
  if (!param) {
    return
  }

// go on with the function }

in caseparamIf the value exists, the function will proceed as expected, otherwise it will stop immediately.

In this example, I return an object describing the error:

function calculateSomething(param) {
  if (!param) {
    return {
      error: true,
      message: 'Parameter needed'
    }
  }

// go on with the function }

What is returned depends on how the code that called the function expects the function to work.

Maybe you can come backtrueIf all is well andfalseIf there's a problem. Or as I showed in the example above, one witherrorBoolean flag, so you can check whether the result contains this attribute (orsuccess: trueProperty in case of success).

Download mine for freeJavaScript beginner's manual


More js tutorials: