Why Javascript needs nullish coalescing operator?

nullish coalescing operator

Javascript provides a double question mark operator (??) which is known as nullish coalescing operator. It is introduced in ES2020. It is a logical operator.

According to MDN, nullish coalescing operator(??) is defined as “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.

Nullisch coalescing is used to set default values when dealing with null or undefined.

In Javascript we already have a logical OR operator || which returns the truthy values.

Here nullish coalescing ?? deals with falsy values.

So, now what are falsy values in javascript?

  • Null
  • Undefined
  • 0
  • NaN
  • False
  • ” “

Using logical OR operator ||:

let a = 0;
let b = 2;
console.log(a||b); //checks the first true value.

Output:0

let a = false;
let b=2;
console.log(a||b); //checks the first true value.

Output: 2

let a = 1;
let b=2;
console.log(a||b); // checks the first true value.

Output: 1

Using nullish coalescing operator:

let a = 0;
let b = 2;
console.log(a??b);

Output: 0

let a = false;
let b=2;
console.log(a??b);

Output: false

let a = null;
let b = 2;
console.log(a??b);

Output: 2

let a = undefined;
let b = 2;
console.log(a??b);

Output: 2

let a = 1;
let b=2;
console.log(a??b);.

Output: 1

For nullish operators only null and undefined are falsy values.

We often use logical operators for assigning a default value to a variable. Nullish coalescing operator is used when you want to evaluate the second expression only when first expression is null or undefined.

Browser Support:

The browsers supported by nullish coalescing operator are:

  • chrome 80
  • firefox 72
  • safari 13.1
  • opera 67
  • edge 80

Key points to remember:

  • We cannot chain with AND && or OR || operator.
  • ?? operator returns the second value if first value is null or undefined.