Nullish Coalescing ft.js

sathithyayogi
2 min readJun 19, 2022

--

Nullish Coalescing ??

The ?? returns the right-side operand when the left-side operand is null or undefined.

const eventData = {eventName:"Free JS Webinar"}console.log(eventData.noOfPeopleAttended ?? "No Data Found")

before that, we use OR operator, but that OR operator returns the right-hand side operand when the left-hand side operand is falsy values like ‘ ’, 0, false , so it won't work in some situations like below.

const eventData = {eventName:"Free JS Webinar",noOfPeopleAttended:0}console.log(eventData.noOfPeopleAttended || "No Data Found")// output No Data Found

the output is supposed to be 0 count, but due to the || OR operator we get right-side operand.

to get rid of these types of issues Nullish coalescing came into the picture.

const eventData = {eventName:"Free JS Webinar",noOfPeopleAttended:0}console.log(eventData.noOfPeopleAttended ?? "No Data Found")// output0

Now the output will be same as expected, yeah it is 0.

these types of OR operator are mostly we use to get value from env variable and assign it to a new variable or config value, due to the || boolean logical operator the left-side operand was coerced to false boolean even falsy value is there, so when we consider as 0 or false or “ ”as a valid value then we can’t use this || operator

when the config value is supposed to be falsy value like “ ” , false or 0, then it returns the ride-side operand, which may lead to bugs, which is difficult to debug.

If you love this blog please leave a 👏🏽.

Happy Coding 🥤 !!!

Feel free to follow me in LinkedIn ❤️

https://in.linkedin.com/in/sathithyayogi

If you have any feedback , mail me at sathithyayogi99@gmail.com.

--

--