Snippet of the Week
This week's snippet is from Hossein Moradi:
console.log(1 === null ?? 1)
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
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
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.
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
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
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. 🥧
- Trickery: a not so well known operator in use
- Key Learning: operator precedence and what nullish coalescing operator does
- Further Reading:
Top comments (0)