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

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

  • right-hand operand value when the left-hand operand is null or undefined
  • left-hand operand value when the 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 to the hash symbol to make it for 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 was introduced in Typescript 3.7 language.

This will be useful for checking the response from consuming API calls Assumed the API calls return 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 these 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, the nullish coalescing operator simplified this

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

if you want to check null values for Employees or departments,

compare with logic OR operator

We already have logic OR operator - ||. This behavior is different from than ?? Operator and comparison

  • ?? considered nullish values - null or undefined, Not boolean values
  • || considered falsely 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 a value is one of null, undefined value, the 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 a falsy value in using || operation.