Nullish coalescing Operator in JavaScript

Nullish coalescing is a new operator in JavaScript. This operator is used for assigning default value when our variable doesn't have any value

Above statement presents a question. If we already can achieve the above mentioned purpose by using the || operator, where does the need to use nullish operator even arise? To answer that, kindly follow the example presented below:

let a = "";
let b = 0;
let c = false;

console.log('Statement-1: ',  a||'unknown value');
console.log('Statement-2: ',  b||1);
console.log('Statement-3: ',  c||true);

Output is

Statement-1:  unknown value
Statement-2:  1
Statement-3:  true

In the above written code

  1. a has value which is ""(an empty string), but still 'unknown value' gets printed

  2. b has value which is 0, but still 1 gets printed

  3. c also has a value which is false, but still 'true' gets printed

As || operator actually works as a conditional operator, it will check for boolean expressions. And according to the JavaScript empty string, 0 and false are always evaluated as false cases.

To solve this issue JavaScript introduced "nullish coalescing operator". It checks values rather than comparing to boolean expressions.

Nullish operator: ??

Replace || with nullish(??) on above code

console.log('Statement-1: ',  a??'unknown value'); // '', empty string
console.log('Statement-2: ',  b??1); // 0
console.log('Statement-3: ',  c??true); // false

We can use nullish coalescing operator(??) with Optional chaining operator(?.)

let obj = {name: 'Biplab', age: 27, hobby: null};
let arr = [1,2,3,4,0];

console.log(obj?.name || 'No name'); // 'Biplab'
console.log(obj?.hobby || []);// []
console.log(arr?.[0] || 'no value'); // 1
console.log(arr?.[6] || 'no value'); // 'no value'

No Comments Yet