Hey guys, this is my first post on web DEV.to, hope you like it.
This will be a 10 part series, in each post I will share some basic problems and concepts that you come across while working. We often miss out on these things though they are part of Javascript, but as you know, we can't keep track of all the new rules.
So you might have seen sometimes some other developer writing ??. Actually, this a Nullish Coalescing Operator(??) which is a logical operator which returns its right-hand side operand when its left-hand side is null or undefined.
"??" <- That looks weird to me, wtf is that Rakshit 🙄
You might be thinking OR operator(||) does the same thing, what is the purpose of ?? then. Yes, you are right the OR operator would also return the right-hand side when the left-hand side would be null or undefined, but there's a big catch to that.
So bud, OR operator(||) would return the right-hand side if the left side would be any falsy value, that's the variation here. Since null and undefined come under falsy values, it would look like it is doing the same thing but there aren't just these falsy values.
Let's look how these falsy values look like:
the number 0
the BigInt 0n.
the keyword null.
the keyword undefined.
the boolean false.
the number NaN.
the empty string "" (equivalent to '' or `` ).
So the crux is the OR operator(||) would return the right-hand side for all the falsy values mentioned above whereas Nullish Coalescing Operator(??) would return the right-hand side only when the left-hand side is either null or undefined.
Isn't it cool....Haha 😁
Well let's try to understand it with some case in point 💬
null || undefined ?? "Elon"; // raises a SyntaxError - use paranthesis to put the left side together!
(null || undefined) ?? "Musk"; // returns "Musk"
(true && false) ?? "Roadster" // returns false
PS: This is a recent addition to the language. Old browsers may need polyfills. Hope next time you will now think before using || operator, whether it is required or if ?? can serve the purpose.
I hope I have been able to make you understand, if not feel free to comment will share more example problems to better explain the concepts. Keep it rolling, coming up with more concepts and problems like these! Cheers guys ✌🏻
Top comments (0)