Code Synopsis logo

What is short circuiting in JavaScript?

The && and || comparison operators have a superpower. You can use them not only to make comparisons but also to return values, and this happens without requiring evaluation of all conditions. JavaScript will short-circuit evaluation of all conditions and return the first value that meets the desired condition.

Short Circuiting with &&

Because it requires all conditions to be true, && is looking for the first falsy value it can find. Evaluating from left to right, as soon as it finds a falsy value, it knows the expression has failed the test. Not all conditions are true. Therefore, it simply returns that value.

var a = true; var b = 'hello'; var c = 0; console.log(a && b && c); // 0 var a = false; var b = 'hello'; var c = 0; console.log(a && b && c); // false

A falsy value is a value that evaluates to false. In JavaScript, there are six: undefined, null, NaN, 0, "" (empty string), and false itself.

Short Circuiting with ||

The || operator requires all conditions to be false, so it is effectively looking for the first truthy value. As soon as it encounters a truthy value there is no need to evaluate the rest of the expressions.

var a = false; var b = 'hello'; var c = 1; console.log(a || b || c); // hello var a = false; var b = undefined; var c = 1; console.log(a || b || c); // 1

A truthy value is a value that evaluates to true. In JavaScript, all values are truthy except the six falsy values listed above.

A Special Feature

Short-circuiting is like inserting a return statement in the evaluation chain, so one can use it to control whether a function is called. While this nifty, I would probably never do this because it is less readable and understandable compared to an if statement.

function myFunction() { return "myFunction was called."; } var a = false; console.log(a && myFunction()); // false a = true; console.log(a && myFunction()); // myFunction is called.

Related posts:

Helpful references:

Have feedback on this topic?