Ahmet Kapusuz

What is Nullish Coalescing Operator in JavaScript?

At the time of writing this blog post, nullish coalescing operator is reached stage4 in TC39 proposals and probably will be included in ES2020. I think nullish coalescing operator will be used widely by developers when it’s available.

Probably you’ve done something like below to set a default value to a variable.

function foo(params) {
  const bar = params.baz || 'defaultValue';
  console.log(bar);
}

If params object doesn’t have baz property or baz property is a falsy value, then bar is assigned as ‘defaultValue’.

foo({}); // defaultValue
foo({ baz: null }); // defaultValue
foo({ baz: false }); // defaultValue
foo({ baz: 0 }); // defaultValue

As you can see all four function calls above will print ‘defaultValue’, because 0 and false is a falsy value in JavaScript. If this is what you want to achieve then it makes sense to use || operator. But if you just want to check if baz is undefined or null, now you can do it easily using new nullish coalescing operator(??).

function foo(params) {
  const bar = params.baz ?? 'defaultValue';
  console.log(bar);
}

Now the output of the function calls will become as below:

foo({}); // defaultValue
foo({ baz: null }); // defaultValue
foo({ baz: false }); // false
foo({ baz: 0 }); // 0

As you see, now we’re able to set default value when baz value is undefined or null.

To learn more about the behaviour of this new operator and some other use cases, check this blog post out. And you can use this babel plugin to experiment it.


Ahmet Kapusuz

Written by Ahmet Kapusuz who lives and works in Amsterdam as a Software Engineer.