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

What is Nullish Coalescing Operator

rahul shukla's photo
rahul shukla
·Jan 10, 2022·

2 min read

We all have some questions about Nullish Coalescing Operator.

what is Nullish Coalescing Operator ?

  • Nullish Coalescing Operator is denoted using "??".
  • ES11 has added the nullish coalescing operator.

Let's understand with a simple expression

x ?? y   // This is expression

In the above expression,

  • If x is either null or undefined then the result will be y.
  • If x is not null or undefined then the result will be x
  • This will help make condition check code easy task

Why JavaScript Needed the Nullish Coalescing Operator

The or Operator ( || ). That work good. but sometimes we want to evaluate when the first operand is only either null or undefined. Now Come Nullish Coalescing Operator solved this problem.

There is some code you can try and understand this operator

let result = undefined ?? "Hello";
console.log(result); //  this print Hello

result = null ?? true; 
console.log(result); // this print true

result = false ?? true;
console.log(result); // this print false

result = 45 ?? true; 
console.log(result); //  this print 45

result = "" ?? true; 
console.log(result); // this print ""


result = [1, 2, 3] ?? true;
console.log(result); // this print  [1, 2, 3]

Notes : if you don't know about operator and operand let see below code

   1 + 2

OPERATOR: Above code, The + is an operator. Operators are used to performing specific mathematical and logical computations on operands. OPERAND: Above code 1 and 2 are operands

I hope you have found this tutorial useful and thank you for taking the time to follow along!