DEV Community

rahul shukla
rahul shukla

Posted on

What is Nullish Coalescing Operator

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 
Enter fullscreen mode Exit fullscreen mode

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 undefine.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]

Enter fullscreen mode Exit fullscreen mode

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

   1 + 2 
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)