How to Exit out of a Function in JavaScript? 3 Great Methods.

When creating functions with multiple possible returning paths we may need to exit out of the function early. This is a frequently encountered scenario when building a function with multiple conditions.

In other programming languages such as PHP and C, an exit() method exists that essentially stops the function from running.

So, how can you exit out of a function in JavaScript?

Functions in JavaScript can be exited by using return,break orthrow. Functions in JavaScript always return something even if not explicitly stated. Behind the scenes, the return statement is implicit if it hasn’t been provided. The default return value for a function is undefined.

// This is actually returns undefined

const getName = (name) => {
  if (name == 'Tommy Vercetti') {
    console.log(name);
   }
}

Using Return

Using return is the easiest way of exiting a function. You can return a value or you just use return by itself.

const getName = (name) => {
  if (name == 'Tommy Vercetti') {
    return;
   }
}

console.log(getName())
// undefined

It’s preferable to return false rather than nothing at all. This allows for any reference to getName() to invoke logic based on a false value or undefined.

This looks cleaner:

if (getName() === false) {
  // find name
}

When compared to :

if (getName() === undefined) {
  // find name
}

Again, this is mainly negligible but it’s important to highlight for readability purposes.

Using Break

Using break is mostly confined to being used within loops but it can also be leveraged to exit from a function. This is achieved by using a label within the function.

const getName = () => {
  getName : {
    console.log("I get logged");
    break getName ;
    console.log("I don't get logged");
  }
};

This approach is definitely less conventional but useful to know that its available to use.

Using Throw

While try and catch blocks are more frequently seen for fetching data, they are perfectly valid in for exiting a function.

const getName = (name) => {
  try {
    //get out of here
    if (name === "Tommy Vercetti") throw "exit";
  } catch (e) {
    // handle exception
  }
};

And there you have it – 3 ways to exit a function, I hope this helped!

Gareth Dunne

Senior JavaScript Engineer and creator of JSdiaries. Passionate about the latest in web technologies and how it can provide value for my clients.