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)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!