Understanding Short‑Circuiting in JavaScript

Hero image for Understanding Short‑Circuiting in JavaScript. Image by TriStar Pictures.
Hero image for 'Understanding Short‑Circuiting in JavaScript.' Image by TriStar Pictures.

In the world of software development, optimisation is often a key concern, which is where "shortcircuiting" comes into play: a simple strategy to make your code more efficient. Understanding shortcircuiting can make your code run faster as well as making it cleaner and easier to maintain.


What is Short‑Circuiting?

Shortcircuiting is an evaluation strategy used in boolean operations that can minimise the number of operations executed, thereby potentially improving performance.

In shortcircuit evaluation, the second argument in a boolean expression is evaluated only if the first argument is insufficient to determine the result. For example, if the first operand is false in an AND (&&) operation, there's no need to evaluate the second operand because the overall result will be false regardless.

You could see this as a safeguarding technique: you programme your code so that it falls out of a costly function as early as possible thus reducing the overall amount of processing required.


Importance in Web Development

Shortcircuiting is a very common pattern that you will find across most (if not all) realms of software development. In web development, however, efficiency can be crucial as we deal with realtime applications, large data sets, or highfrequency operations, all in the front end, running on whatever resource the visitor's browser allows us to use.

Shortcircuiting helps to make operations more efficient, improving the performance of our applications and websites.


Short‑Circuiting in JavaScript

In JavaScript, we have access to shortcircuit evaluation by way of its logical operators: && (AND) and || (OR).

Using &&

const a = false;const b = true;if (a && b) {  console.log('Both are true.');} else {  console.log('At least one is false.');}//=> 'At least one is false.'

How It Works

In this example, the if statement checks if both a and b are true. However, JavaScript recognises that a is false and immediately knows that a && b cannot be true. With this being the case, it shortcircuits and never even checks b, instead proceeding directly to the else block.

Using ||

const c = true;const d = false;if (c || d) {  console.log('At least one is true.');} else {  console.log('Both are false.');}//=> 'At least one is true.'

How It Works

In much the same way as using AND above, here the || operator starts on the left, evaluating c first. Since c is true, we again shortcircuit; the JavaScript doesn't attempt to evaluate d at all and heads straight to executing the if block's content.

Using the Ternary Operator (? : )

Although shortcircuiting is commonly used with logical operators, it can also be implemented using conditional (ternary) operators. The essential concept remains the same: minimise unnecessary evaluations to optimise performance, but the implementation is a little more complex. For example:

const value = null;const defaultValue = 'Default Value';const result = value || defaultValue;console.log(result);  //=> "Default Value"

How It Works

Here, we have a variable value set to null and a defaultValue set to "Default Value".

We then use the ternary operator to set result to value if value is truthy, otherwise to defaultValue.

The expression value ? value : defaultValue checks value first. If value is falsy (which it is, because it's null), JavaScript immediately knows it should use defaultValue and doesn't even have to consider the other option (value).


More General Short‑Circuiting Practices

Outside of the explicit cases I've described above, the term "shortcircuiting" can also refer to the more general programming practice of simply exiting a function as soon as you know the result, allowing the program to avoid doing additional unnecessary work. For us frontenders, this is particularly useful for resourceexpensive functions.

In this broader sense, shortcircuiting often takes the form of "guard clauses" or "early returns" at the beginning of a function. These are conditions that, if met, allow the function to terminate immediately.

Here's a quick example:

const findElement = (arr, elem) => {  // Short-circuit if the array is empty  if (!arr || arr.length === 0) {    return null;  }  // Short-circuit if elem is undefined  if (elem === undefined) {    return null;  }  for (let i = 0; i < arr.length; i++) {    if (arr[i] === elem) {      return i;  // Found the element    }  }  return null;  // Element not found};

How It Works

In this example, the function findElement first checks two conditions:

  1. If the array is empty or not provided (!arr || arr.length === 0), it shortcircuits and returns null.
  2. If the element elem is undefined, it shortcircuits and returns null.

These checks occur before the function enters the for loop to search for the element, and by doing so, the function avoids the potentially expensive loop operation if one of the initial checks fails.

Commonly (and outside of writing code to illustrate examples), you would also put all of these escape conditions together into a single if, using the example from before:

// Short-circuit if the array is empty, or elm is undefinedif (!arr || arr.length === 0 || elem === undefined) {  return null;}

Conclusion

In addition to the specific behaviour of logical operators like && and ||, the term "shortcircuiting" can also refer to this broader pattern of efficiently exiting a function as soon as you know the result.

I should also say here that some of these types of patterns can be avoided by using required properties with TypeScript, although it's probably best I don't drop another large block of code on you as an example...


Categories:

  1. Development
  2. Guides
  3. JavaScript