Ever wondered how the null coalescing operator || works in JavaScript?

For those who are wondering what exactly the null coalescing operator is, consider the following example:

var a = null;
var b = a || 10;
console.log(b); // It will log 10

It is very probably that you already used such code in your programs. In the previous example, with the || operator we are practically set the number 10 to variable b, if the value inside variable a is null.

But in which cases exactly will b have this “fall-back” value as its value? How about the following example, what will the value of b be?

var a = 0;
var b = a || 10;
console.log(b); // It will log 10

If you said 10, then you guessed right. But, 0 is not null, isn’t it? So we can easily conclude that the term null coalescing operator is just a name-convention which is borrowed from other programming languages, such as C#.

So what exactly does the || operand does? And when the second part of this operator is called?

The || performs a boolean-test on the first value, in this case 0. We know that when 0 is coerced (change the “type” of the value (More information about coercion here)), is coerced into false. The same counts for null, undefined, ““. Since the left side of the expression is false, the operator will also evaluate the right side of the expression, which in this case is true, because 10 is a non 0 number.

The || is exactly the same operator you are using in your if clauses. There, you can have multiple || chained. The same principle works also for these cases:

Consider the following example:

var a = 0;
var b = null;
var c = a || b || 5;
console.log(c); // It will log 5

As you can see the operation went till the right-most operand since the previous ones were always coerced into false. The returned value is not true but the value it self. In this case 5.

So the next time you see something like the following

var a = 0;
var b = null;
var c = 5;

if (a || b || c) {
    console.log("This will be printed");
}

you know that the operation inside the if clause went till the right-most operand and since this operand was coerced into true the console will log the message. So the previous snippet is actually the equivalent to the following:

if (5) {
    console.log("This will be printed");
}

and since 5 is implicitly coerced to true, the code enters the if clause.

That’s it. Now you know the exact behavior of the || operator.

comments powered by Disqus