Es11 features- Nullish Coalescing Operator

Nullish Coalescing Operator is a new feature in ECMAScript2020 to latest javascript language feature, and it’s symbol is ?? i.e double question mark.

It is a logical operator applies two operands, returns its value of

  • right hand operand value when left hand operand is null or undefined
  • left hand operand value when left hand operand is not null or undefined

This will be useful for default to fallback value when object properties are null or undefined

**Syntax **

Left Operand ?? Right Operand

Variables are added hash symbole to make it private use in a class. Syntax

#variable

Let’s see an example

const result1 = null ?? "default1";
const result2 = "" ?? "default2";
const result2 = 11 ?? 0;

console.log(result1); // default1
console.log(result2); // default2, Empty string is not equal to null or undefined
console.log(result2); // 11

Nullish Coalescing usage in Typescript example

Nullish Coalescing introduced in Typescript 3.7 language.

This will be useful for checking response from consuming API calls Assumed the API calls returns response and the response nested structure as follows

const result = response.employe.department.id; if employe or department is null or undefined, It throws an error TypeError: Cannot read property ‘employe’ of undefined. To avoid this errors, have to validation check as per below

let id;
if (response.employe && response.employe.department) {
  id = response.employe.department.id;
}else{
   id="Id not found"
}

so id always has value either valid value or default fallback value. To avoid this length code check, nullish coalescing operator simplified this

const id = response.employe?.department?.id ?? "Id not found.";

if you want to check null values for Employee or department,

compare with logic OR operator

We already have logic OR operator - ||. This behaviour is different than ?? Operator and comparision

  • ?? considered nullish values - null or undefined, Not boolean values
  • || considered falsey values - null or undefined or NaN, or "" or 0

Let’s see an example of both || and ??

let result = value ?? 0;
console.log(result) 

if value is one of null ,undefined value, default value is zero

let result = value || 0;
console.log(result) 

if value is one of null ,undefined,0,empty string -"",NaN value, default value is zero.

empty and "" are treated as falsy value in using || operation.