How to exit a JavaScript function

Reading Time: 2 minutes 🕑

Last updated: August 29, 2022.

There are situations where it makes sense to exit the execution of a function call early.

For example, you may have a function that does something with a passed in value. If no passed in value is present, it may make sense to immediately stop the function.

You can exit a function by using the return keyword. Once the return keyword is called, execution of the function stops and no further code is processed:

const div = document.getElementById('my-element');

function makeRed(inputElement) {
  if (!inputElement) { // if element doesn't exist in the DOM...
    return; // ...return is called, stopping further the execution of the function
  }
  inputElement.style.backgroundColor = 'red'; // this line runs only if element exists in DOM
}

makeRed(div); // undefined OR <div id="my-element"></div>

You can also return a value. The behavior will be the same except that the function now returns the value instead of undefined.

It is often a good idea to return the Boolean value true here so you can easily evaluate it as truthy or not in an if statement:

const div = document.getElementById('my-element');

function makeRed(inputElement) {
  if (!inputElement) {
    return true;
  }
  inputElement.style.backgroundColor = 'red'; 
}

// Handle result:
const res = makeRed(div);
if (res) { // if value of res is truthy...
  console.log("No element found!"); // ...the messgae is logged!
}

The reason for returning true and not false is that a JavaScript function will always return a value. And if no return value is explicitly specified, the return value of a function will be undefined.

By returning true, the outcome is either truthy (true) or falsy (undefined). This makes for easy evaluation of the outcome using an if statement.

Exit function and stop script

By throwing an error rather than returning value, you can stop the function as well as any further code execution:

const div = document.getElementById('my-element');

function makeRed(inputElement) {
  if (!inputElement) {
    throw new Error("Well, this is awkward...");
  }
  inputElement.style.backgroundColor = 'red'; 
}

makeRed(div);

If an error is thrown, the message contained in the error message will appear in an error message in the console.