Destructuring Tweets – Episode 12 – Coalesced False
Look who managed to head to my blog only to find himself reading an article about a tweeted Javascript quiz. In this series, I try to break such down, and this post features a lesser-known but often useful operator: Nullish Coalescing!
The Snippet
console.log(1 === null ?? 1)
This time we have a super quick one. It logs a logical expression to the console. And that's pretty much already it!
The expression itself consists of two parts. The first one compares null to 1. The result is the left-hand side operand of a so-called “Nullish Coalescing Operator” typed as ??.
The right-hand side operand is, again, just 1.
The Output
The output is also pretty straightforward. At least if you know what a “nullish coalescing operator” does. This expression will log false to the console.
The Analysis
For the analysis, we start with the Strict Equal Operator (===) as it takes higher precedence (“will be evaluated before”) than the mysterious two question marks. And it's also reasonably easy. Comparing null to 1 will undoubtedly result in false, won't it?
What's left looks something like: false ?? 1.
So far, so good. Now comes the fun part. A Nullish Coalescing Operator works in its core like a Logical Or (||). However, instead of checking for falsy values, it only validates for nullish ones! That means either null or undefined. To get this straight: it will return the left-hand side value if it's not “nullish” or the right-hand side value if not.
And that is the reason false gets printed to the console. 🥧