How to use the nullish coalescing operator (??) in Javascript

Image source: Negative Space/ @negativespace on Pexels

he nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

Simply put, the nullish coalescing operator let’s us truly check nullish values instead of falsey values.

In JavaScript, a lot of values are falsey, like the number zero, an empty string, undefined, null, false, NaN etc.

Check the code below:

console.log(NaN ? "truthy" : "falsy"); // falsy
console.log("" == false); // true
console.log(0 == false); // true
console.log(null ? "truthy" : "falsy"); // falsy
console.log(undefined ? "truthy" : "falsy"); // falsy
console.log(false == false); //true
console.log(-0 == false); // true
console.log(document.all ? "truthy" : "falsy"); // falsy

// NaN, undefined and null are not really false
console.log(NaN == false); //false
console.log(undefined == false); // false
console.log(null == false); // false
console.log(document.all == false); // false

NaN, undefined, null and document.all are not really equal to false but they are falsey, that’s why I didn’t make a check against false and I used a condition instead.

With this in mind, let’s now look at some examples in which we’ll first use the OR operator and then the nullish operator:

// using the logical OR (||) operator

const or_printSomething_1 = null || "random string";
console.log(or_printSomething_1); // prints "random string"

const or_printSomething_2 = undefined || "another random string";
console.log(or_printSomething_2); // prints "another random string"

const or_printSomething_3 = 0 || "what? another string?";
console.log(or_printSomething_3); // prints "what? another string?"

const or_printSomething_4 = false || "ok? too many strings!";
console.log(or_printSomething_4); // prints "ok? too many strings!"

// using the logical nullish (??) operator

const nullish_printSomething_1 = null ?? "random string";
console.log(nullish_printSomething_1); // prints "random string"

const nullish_printSomething_2 = undefined ?? "another random string";
console.log(nullish_printSomething_2); // prints "another random string"

const nullish_printSomething_3 = 0 ?? "what? another string?";
console.log(nullish_printSomething_3); // prints 0

const nullish_printSomething_4 = false ?? "ok? too many strings!";
console.log(nullish_printSomething_4); // prints false

As you can see, when using ||, the left side is always evaluated to false and the right side gets printed to the console. When using ?? and the left side is equal to undefined or null, only then the right side is returned.

Being a feature of ES2020, the nullish coalescing operator is not fully supported by all browsers, so you can check for compatibility here:

Leave a Reply

Your email address will not be published. Required fields are marked *