Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 23, 2021 11:25 am GMT

Everything you need to know about nullish coalescing

Nullish coalescing is new Javascript feature of ES11 (aka ECMA Script 2020).The nullish coalescing operator looks like this ??

Truthy and Falsy values

Before proceeding further,, you need to know about truthy and falsy values in Javascript to understand better. Basically, false, 0, -0, BigInt(0n), empty string('' or "" ), NaN, null, undefined are considered as falsy values in Javascript.
Other than this, as you guessed, is truthy.
It's important to remember this , not only for nullish coalescing but also it will be very useful as you dive more deeper in Javascript. To prove you that these are treated as falsy values, try to console.log every falsy values mentioned above. Like this ,

  console.log(Boolean(0)) // would return false

The Traditional || operator

Have you ever used logical OR (||) operator for setting a default value if the varible doesn't exist? Let me give an quick example,

const obj = {  name : undefined  age : 45}console.log(obj.name || 'default name') // default name

From the above example, it is pretty straightforward that we set a default value if the name doesn't exist. This technique is called as fallback mechanism, and it is often used by developers out there.
But it is important to know how || operator works. Its simple.

The || operator checks for first truthy value. Take a close look at the example below

let firstName = undefinedlet secondName = nulllet age = 0let nickName = ''let orignalName = 'Miller'console.log(firstName || secondName || age || nickName || orignalName || true) // Miller

Now, you might think, why does it return Miller instead of 0?
It is because, except orignalName variable and Boolean true, every other variable is considered as falsy value as i said before.

Think
originalName is returned eventhough true is also a truthy value

But, if u try to replace the || operator with ?? operator, it would return 0.

console.log(firstName ?? secondName ?? age ?? nickName ?? orignalName) // 0

What does ?? do ?

According to MDN docs, nullish coalescing 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".

For example,

const result = x ?? y ; // In the above code, // -> y is returned , only if x has null or undefined (not ''). // -> x is returned if it has values other than null or undefined (including '').

The syntax looks confusing at first. the above example is same as below :

const result = (x!== undefined && x!== null) ? x : y;

This should make sense if you are familiar with ternary operator in Javascript. If not, refer this MDN docs.
The most common usecase of ?? is to set or provide a default value for a potentially undefined varibles. What do u mean by that ? Lets look at some more examples ,

Note
There are only two nullish values (null and undefined)

console.log(0 ?? 10) // 0  since neither of them is a nullish valueconsole.log(2 ?? 3) // 2 , since neither of them is a nullish valueconsole.log( null ?? 'john') // john , since null is a nullish valueconsole.log( undefined ?? 'john') // john , since undefined is also a nullish value

However, here is the case where it differs from ||

console.log(0 || 10) // 10 since, || operator looks for first truthy value, `0` being a falsy value is ignored and so 10 is printed

Ok, then , why does the code below (from one of the previous example) returns 0 ?

console.log(firstName ?? secondName ?? age ?? nickName ?? orignalName) // 0

Let me breakdown ,
firstName is undefined , a nullish value ,so it moves to secondName
secondName is null , a nullish value , so it moves to age
age is 0 , which is not a nullish value , so it returns age.

Make sense ? I know it looks confusing at first, it will make more sense as you get used to it.

|| vs ??

The main difference is,

  • || returns the first truthy value
  • ?? returns the first defined value

Challenge

To test your understanding , try to guess the correct answer for the below exercise before scrolling down to see the solution

let groceries = {  item1: {    name: 'apple'    color: 'red',    quantity: 5  },  item2 : {    name: ''    color: undefined    quantity: null  }}console.log((groceries.item2.color ?? groceries.item1.price ?? groceries.item1.name) || groceries.item1.color) 

Solution

If your answer is apple, congrats , You are correct. Don't worry if you guessed it wrong. This will make more sense when you get used to it. Also, I will provide some additional resources to learn more about Nullish coalescing if this tutorial confuses you.(hopefully not , ig)
Thanks for reading my post

Additional Resources


Original Link: https://dev.to/nithish_13/everything-you-need-to-know-about-nullish-coalescing-3p63

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To