My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Nullish Coalescing  Operator (??)

Nullish Coalescing Operator (??)

Deactivated User's photo
Deactivated User
·Jan 10, 2022·

2 min read

The nullish coalescing operator (??) is 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. It was added to the standard in ECMAScript's 11th edition.

This operator can be compared with the logical OR (||) operator, which returns the right-hand side operand if the left operand is any falsy value. Falsy value present in JavaScript are (0, '', NaN, null, undefined) .

Syntax of Nullish Coalescing operator

leftExpresion ?? rightExpresion

See below examples for a better understanding

const firstName = null ?? 'default';
console.log(firstName);
// output: "default"

const anyNumber = 0 ?? 10;
console.log(anyNumber );
// output: 0

Now we will compare Nullish (??) operator with OR (||) operator and see the difference between them

1) With String

const someText = '';  
// "" i.e. Empty string considered as false value 

const outputWithOR = someText || 'Hello world';
console.log(outputWithOR); 
// Hello world

const outputWithNULLSIH = someText ?? 'Hello world';
console.log(outputWithNULLSIH); 
// '' ( Because someText is neither undefined nor null)

2) With Number

let count = 0;

let outputWithOR = count || 25;
console.log(outputWithOR ); 
// 25

let outputWithNULLSIH = count ?? 25;
console.log(outputWithNULLSIH ); 
//0

Conclusion

The nullish coalescing operator is only returning the second operand when the first one evaluates to either null or undefined (but no other falsy values).

End note

I hope you have got a clear idea of the Nullish Coalescing 0perator! Would love to know your feedback in the comments!

If you want to read more about it : Click Here