Nullish coalescing operator `??`

Nullish coalescing operator `??`

In this article we are going to understand about Nullish coalescing operator (??).

Let's get started🚀

Fun Fact

This operator it self is a question mark. ??

question-mark-animation.gif

The Nullish coalescing operator ?? , is a short-circuiting operator, like || or &&, which will return the righthand side operator, if the left-hand side operator is nullor undefined. Otherwise, it will return the lefthand side operand.

Note that When ?? is used, the falsy values (empty string (''), 0, false, NaN) will still return the lefthand operand. Whereas in || or && it will return the right side operand.

Let us see some examples:

let user;

data = user ?? "Anonymous"  // return "Anonymous"

user = "John";

data = user ?? "Anonymous"  // return "John"

user = "";

data = user ?? "Anonymous"  //  return ""

Hope you understand this by now.

Now let's see it's usage in our real life examples:-

function greeting(user) {

  const name = user.name ? user.name : "John";  

  return `Welcome ${name}`;
}

In the above function, we have a user argument. If the user object doesn’t contain name, then it will result in undefined. In older versions of JavaScript, we handled this with above pattern.

But with NULLISH COALESCING OPERATOR, We can do the following code:

function greeting(user) {

  const name = user.name ?? "John";  

  return `Welcome ${name}`;
}

Got to learn new thing, Right!!😉

Now the question comes

Why do we need nullish coalescing? When using short-circuiting operators like && and ||, we need to handle all falsy values.

|| --> This will return the first truthy value it finds, Otherwise return the last falsy value.

let a = 100,  b = 0 , c = null

a || c  // return 100

b || c  //  return null

Now, Let's Understand the above snippet:

In the first case, it will return the first truthy value. In the second case, it will return the last falsy value

[Reference:- In JS : undefined, null, NaN, 0, "" (empty string), and false are all the falsy values]

&& --> This will return first falsy value it finds. Otherwise, return last truthy value.


let a = 100,  b = 0 , c = null

a && b && c  // return 0

a && z // return 100

So For Cases like this, the best solution is Nullish coalescing operator. For Example:

undefined ?? 0 ; //0

null ?? 0 ;      // 0

false ?? true  // return false;

0 ?? 1 // return 0

No Chaining with && and || operator.

It is not possible to directly combine both AND && and OR Operator || with ??

null || 0 ?? "dev"  //SyntaxError

true && undefined ?? "dev" //SyntaxError

Parenthesis can be the solution for this :

( null || 0 )?? "dev"  //0

You have came rading a long way. Clap for yourself.

clap-applause.gif

Hope you got to learn some new things and understood Nullish Coalescing operator. Thankyou for reading.

Â