JavaScript Short-Circuit Evaluation

Published Mar 01, 2018Last updated Mar 18, 2018
JavaScript Short-Circuit Evaluation

Having worked with JavaScript for quite some time now, I have seen the various ways one can do something to ultimately achieve the same result. I'll be discussing short-circuit evaluation in this post.

This feature is available in various languages but the implementation might be different. For brevity, I'll be dealing specifically with JavaScript.

In short-circuit evaluation, the second argument is evaluated only if the first argument does (not) satisfy a given condition.

Logical AND (&&)

Logical AND (&&): When a certain condition evaluates to false, the corresponding condition(s) is/are not evaluated when the && operator is used.

Given the following code snippet:

let username;

if (Meteor.user()) {
  username = Meteor.user().username;

We could use the && operator to reduce the amount of lines we write as follows:

const username = Meteor.user() && Meteor.user().username;

// ES6 destructuring
const { username } = Meteor.user() && Meteor.user();

This is read as: if Meteor.user() is defined, assign the value of the username property from Meteor.user() to the username variable.
Looking at this code, we have significantly reduced the number of lines we type to get the same thing done.

Logical OR (||)

Logical OR (||): When a certain condition evaluates to true, the corresponding condition(s) is/are not evaluated as they would be true when the || operator is used.

Given the following snippet:

const name = null;
let language;

if (name) {
  language = name;
} else {
  language = "JavaScript";

In the snippet above, I am checking that name has a value. If it does, I assign the value to the language, otherwise I provide a default value JavaScript.

Using ||, we could significantly reduce that whole code to just one line as follows:

const lanaguage = name || "JavaScript";

There's not much difference in the code above, except that it is shorter. It does the same check for name, providing a default value if name is not defined.

Operator chaining

The operators (&& and ||) can be chained together to create a kind of if...else condition.
Using the first example above:

const username = Meteor.user() && Meteor.user().username || "code";

This translates to checking for the existence of Meteor.user(). If true assigns Meteor.user().username to username variable, otherwise assigns "code" to username.

NOTE: Using the short-circuit operator chaining is not advised, as this can make your code less readable. Using operator chaining is disallowed in some JavaScript style guides.

This brings us to the end of this post. I hope you've learned something new. Have a comment/question? Kindly drop a comment/suggestion or question in the comment thread.

Discover and read more posts from John Kennedy
get started