Sign in
Log inSign up
Nullish Coalescing Operator  
  
                    '??'

Nullish Coalescing Operator '??'

Ruchi Goswami's photo
Ruchi Goswami
·Jan 15, 2022·

2 min read

Two question marks (??) put side-by-side in JavaScript - this fairly new logical operator in JavaScript is available on most newer version browsers and is called Nullish Coalescing Operator. It is similar to ternary operator but handles a specific case. Let's explore these fancy words in some detail.

The nullish coalescing operator (??) is a logical operator that returns the right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
(from MDN Web Docs)

Syntax

leftExpression ?? rightExpression

Example 1

let leftExpression = null;
let rightExpression = "I like emojis";
let someExpression = leftExpression ?? rightExpression; 
console.log(someExpression); 

// I like emojis

Example 2

let box1 = undefined;
let box2 = "bootcamp";
let someBox = box1 ?? box2;
console.log(someBox);

//bootcamp

Example 3

let erasers= 0;
let pencils = 11;
let totalPieces = erasers ?? pencils; 
console.log(totalPieces); 

// 0

In examples 1 & 2, left-side operand is null or undefined, therefore, we get the right-side operand as a result. However, in example 3, left-side operand is returned even if it is '0'. This is because nullish coalescing operator specifically checks for "null" or "undefined" and not just any falsy values.

Falsy values in javaScript are: null, undefined, " " (empty string), 0 , NaN, false

For any falsy values except null or undefined, nullish coalescing operator will return left-hand side operand. See example below.

Example 4

let myChoice = false;
let fruit = "apple";
let check = myChoice ?? fruit;
console.log(check);    //false

let check2 = myChoice || fruit;
console.log(check2);   //apple

We can also assign a default value on right-hand side operand. In case the variable is not yet initialized, or is null, the default value will be shown as an output. See example below.

Example 5

let name;
let checkName = name ??  'A valid name is required' ;
console.log(checkName); 

// 'A valid name is required'

Using ?? with logical operators && or ||

Unless we use parenthesis, it is not possible to use logical operators directly with ?? It will raise a syntax error otherwise.

let flower = null || undefined ?? 'lotus' ;  
console.log(flower);   // Uncaught SyntaxError: Unexpected token '??'

let flower = (null || undefined) ?? 'lotus' ;  
console.log(flower);   // lotus

To conclude, this operator is a great choice for providing default values when you’re certain the condition is nullish, otherwise use the OR operator ( || ).

Thank you for reading. Please provide feedback if you have any.

References: