Properly Exit from a JavaScript Function. or Early...

Is there a correct way to exit a function? How should a skilled programmer exit a JavaScript function? Let's explore together how JavaScript exits function properly or stops the execution of a function.

Properly Exit from a JavaScript Function. or Early...
Photo by Izzad Syah / Unsplash

Technically, in JavaScript, you don't need to do anything special to exit a function. A function in JavaScript that doesn't contain a return statement will exit with the default return value undefined. If the function is not recursive (a function that calls itself) or in an infinite loop, it will return some value one way or another. However, there are points to consider when writing quality code. Let's first see different ways to exit from a JavaScript function.

Methods of Exiting a Function

return

The most obvious way to exit from a function is using the return keyword quickly.

  function add(a, b) {
    return a + b;
  }

throw statement

function divide(a, b) {
    if (b === 0) throw new Error("Division by zero.");
    return a / b;
}

It's beneficial to note here that it is possible to handle exceptions in a try-catch block for a particular condition when it is not a fatal error. You may want to catch throw and return a default value.

break (huh?!)

In some sources, the break statement is also mentioned as a way to exit a function. These sources provide an example similar to the following example:

function getData() {
  body: {
    console.info("This is not the way!");
    break body;
  }
}

If you examine the above code, you can see that the break body statement doesn't exit the function; it exits the block named body. To understand this better, let's look at the following non-working (faulty) code:

body: {
  console.log("This code does not work at all!");
  function getId() {
    break body; // SyntaxError: Undefined label 'block1'
  }
}
getId();

Similarly, the following code will also not work:

function getId()  {
  console.log("This code does not work at all!");
  break; // SyntaxError: Illegal break statement
}
getId();

break is a statement to exit from the current loop when a specific condition is met.

exit (nuke)

This is a node.js specific way to exit from the node.js process. It exists from the function and terminates the program execution completely with the specific value we provided as an exit code. If you stop script execution with a non-zero value, it means an error occurred. See the following code block:

function add(a, b) {
  process.exit(1); // Stops code execution with an error code.
}

Best Practices

So, how should we exit a function? We can see a few points to pay attention to when we examine it from a code quality perspective. While these points are not strict rules of the JavaScript language, following them can be beneficial, especially if you're uncertain about what you're doing.

Consistency

JavaScript allows a function to return different data types. For example, the following code returns either a number or a string based on a given condition:

function getValue(condition) {
  if (condition) return 1;
  else return "a";
}

While the above code is not technically problematic in JavaScript, it's a disturbing example of code quality. Unless there's a particular reason, a function should return the same data type in all cases. Otherwise, bugs that are hard to find might appear in the code that uses this function.

Single Exit Point

A function should not have multiple exit points. It's hard to follow early exit points if some are in the middle of the function.

This rule is quite debatable and can vary based on personal opinions. I must confess that I don't strictly adhere to this rule. This rule assumes that functions with long bodies are difficult to follow. However, a function's body should be short; if it's long, it should be divided into sub-functions. Still, I believe sharing this rule can be helpful here.

function getData() {
   const condition = false;
   // Some code.
   // Some code.
   if (condition) return 3;
   const something = false;
   // Some code.
   // Some code.
   // Some code.
   if (something) return 2;
   const other = false;
   // Some code.
   // Some code.
   // Some code.
   if (other) return 1;
   // Some code.
   // Some code.
   // Some code.
   return 0;
}

No Empty Return

Another debatable rule. An explicit return undefined is advisable over an empty return statement because a blank return might be distracting and could accidentally have a value added to it.

function getData(condition) {
  if (condition) return undefined;
}

ESLint

We can check all return statements automatically using ESLint. ESLint is a must-use tool that statically analyzes your code to find problems quickly. There are multiple ESLint rules to check the quality of return statements. The following are the most useful ones, but you can find more if you make a Google search.

Would you like to share your thoughts about how to exit from a JavaScript function? Post your thoughts and comments below.