This page looks best with JavaScript enabled

Using Nullish Coalescing Operator

 ·   ·  ☕ 6 min read

ES2020 introduced nullish coalescing operator. We will see just how and where can you find use for it?

What it is?

Nullish coalescing operator (??) is introduced in the newest Javascript specification. It’s primary design goal is quite simple - provide a way to check for nulls to return true or false values from an expression.

The operator follows in the footsteps of shorcircuitinng operators && and || to provide developers with a reliable way of checking for -

  1. Null values
  2. Differentiating between nulls and values that exist but are falsy

The basic usage is simple.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function check(planet) {
  return planet["awesome"] ?? true;
}

let earth = { awesome: true };
let pluto = { awesome: false };
let mars = {};

console.log(check(earth)); // true
console.log(check(pluto)); // false
console.log(check(mars)); // true

Null coalescing operator evaluates to true only for null and undefined. And, any evaluation of the expression is skipped if the left-most expression evaluates to null or undefined (similar to truthy checks in ||).

The results would have been different if you had used a simple || operator without null checks.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function check(planet) {
  return planet["awesome"] || true;
}

let earth = { awesome: true };
let pluto = { awesome: false };
let mars = {};

console.log(check(earth)); // true
console.log(check(pluto)); // true. Wait what?
console.log(check(mars)); // true

Why is null coalescing operator required?

Javascript does not require you to specify types, but they are implicitly assumed by the runtime.

Let us take this simple example.

1
2
3
4
5
6
7
const a = "abc",
  b = 1,
  c = true;
if (a == "abc" && b == 1 && c == true) console.log("so true");

// output
// so true

Or, you could just use -

1
2
3
4
if (a && b && c) console.log("so true");

// output
// so true

“Free typing” allows us to do some magical (horrifying to some) things. The above block script executes because the string and number are converted to boolean, and rules are automatically applied to convert values to boolean for evaluation.

We could make the script more readable by shortcircuiting it.

1
return planet["awesome"] || true;

If planet has awesome property set return that property, OR return true.

While this is awesome and all, you can see where it can go wrong.

1
2
3
4
5
6
7
8
let pluto = { awesome: false };
console.log(check(pluto)); //

function check(planet) {
  return planet["awesome"] || true;

  // true for pluto
}

Even when we specify pluto is not awesome, our program (rightfully) assumes it is. This happens because of the way || evaluates the expression-

  1. Start from left to right
  2. Check if first expression is true. Return true if it is
  3. Check if next expression is true. Return true if it is
  4. … and so on till the entire expression is evaluated

In our case -

1
return planet["awesome"] || true;

We pass pluto to the function -

  1. pluto['awesome'] is false
  2. OR moves to the right, and gets true
  3. Expression returns true

Our favourite way to solve this so far has been -

1
2
3
4
5
6
7
8
let pluto = { awesome: false };
console.log(check(pluto)); //

function check(planet) {
  return planet.hasOwnProperty("awesome") ? planet["awesome"] : true;

  // false
}

If pluto has a prop called awesome, return that. Or, return true.

Null coalescing operator simplifies this check.

1
2
3
4
5
6
7
let pluto = { awesome: false };
console.log(check(pluto)); //

function check(planet) {
  return planet["awesome"] ?? true;
  // false
}

We are now effectively saying if awesome prop is not null, return that. Else, return true.

How does nullish coalescing operator behave under pressure?

Quite well, actually.

Nullish coalescing operator acts very similar to ||, but, we are effectively checking for nulls.

1
2
3
4
5
6
console.log(null ?? true); // true
console.log(undefined ?? true); // true
console.log(false ?? true); // false

console.log(null || true); // true
console.log(false || true); // true

Now, consider these interesting expressions -

1
2
3
4
5
6
console.log("abc" ?? true); // "abc"
console.log("" ?? true); // ""
console.log(1 ?? true); // 1
console.log(0 ?? true); // 0
console.log(true ?? true); // true
console.log(false ?? true); // false

Use Cases

You can use nullish coalescing operator with ES2020. It is supported in Node 14+ and in all major browsers. Using variables for falsy checks without worrying about whether the return value is false simplifies our code.

A few use cases are outlined below.

1. Truthy checks alongside null values

This is the simplest use case, but one that you probably will never use.

1
2
3
const planet = "earth";
console.log(planet ?? "no planet");
// earth
2. Prop checks

This will be the most likely use case. Use this new operator and avoid null checks.

1
2
const earth = { awesome: true };
console.log(earth["awesome"] ?? true);

You will do this if you don’t want to use the new optional chaining operator. Both the operators do the same thing differently.

Optional chaining operator (?.) offers a convenient way to use props without ever caring about the object is valid. For e.g. consider this code ..

1
2
3
const planet = null;

console.log(planet.earth.name); // error

To avoid the null game, we were forced to introduce our own checks like so -

1
2
3
const planet = null;

if (planet && planet["earth"]) console.log(planet["earth"]["name"]);

But, now we can rock the world with a cooler way to do the same thing.

1
2
const planet = null;
console.log(planet.earth?.name?.toUpperCase()); // no error :)
3. Arg checks

Another strong use case - thanks to Javascript’s typing powers.

1
2
3
function isPlanet(planet) {
  console.log(planet["type"] ?? true);
}

Again, this could be better served by optional chaining depending on your use case.

When not to use this operator?

Nullish coalescing operator is of course no hammer, and it does not offer you peace of mind even with the narrow coverage it offers.

Can’t chain with AND / OR
1
2
console.log(    true || planet ?? "ok");
// syntax error
Support is limited

You cannot go crazy with nullish coalescing operator.

  • Node v14+ is required
  • Not supported in IE (are you still using IE?), Firefox for Android, Opera for Android. Check browser compatibility to know current status

Fin

That’s about it folks. Start coding cool stuff!

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things