💾 Archived View for wilw.capsule.town › log › 2020-11-20-nullish-coalescing.gmi captured on 2023-09-08 at 16:16:53. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-04-19)

-=-=-=-=-=-=-

🏡 Home

Back to gemlog

JS Tidbit: Nullish Coalescing

Posted on 20 November 2020

This short post introduces a useful JavaScript operator to help make your one-liners even more concise.

The specification [1] was added formally in the 11th edition of ECMAScript. It is implemented as a logical operator to selectively return the result of one of two expressions (or operands) based on one of the expressions resolving to a "nullish" value. A nullish value in JavaScript is one that is `null` or `undefined`.

1

In particular, the operator - given by `??` - will return the right-hand side if the left-hand expression resolves to `null` or `undefined`, and otherwise returns the left-hand side.

const x = y ?? z;

In the example above, `z` will be returned if `y` is "nullish", and otherwise `y` will be returned.

Nullish coalescing is similar to (but stricter than) the more commonly-seen logical OR operator - given by `||` - which returns the result of the right-hand side expression if the left-hand side resolves to any falsy value, which includes nullish ones in addition to the boolean `false`, empty string (`''`), `0`, `NaN`, etc.

More info is available on MDN [2] and Wikipedia discusses null coalescing in other languages [3].

2

3

Reply via email

Back to gemlog