DEV Community

Cover image for Destructuring Tweets - Episode 12 - Coalesced False

Posted on

Destructuring Tweets - Episode 12 - Coalesced False

S.P.D.S.V.B.E.E.V.! Look who managed to head to only to find himself reading an article about a tweeted Javascript quiz. In this series, I try to break such down and this week features a lesser-known but often useful operator: Nullish Coalescing!

Snippet of the Week

This week's snippet is from Hossein Moradi:

console.log(1 === null ?? 1)
Enter fullscreen mode Exit fullscreen mode

This week 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 of that 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. 🥧

Snippet Summary

Top comments (0)