codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Green ceramic bowls containing raw indigo and marigold for dyes
Dyes made from natural materials coalesce to form the pigments used to color wool in Oaxaca, Mexico. Photo credit: Mark Brouch

Member-only story

A Practical Example of Nullish Coalescing

Mark Brouch
codeburst
Published in
4 min readJun 3, 2020

--

Nullish coalescing is a brand new logical operator (??) for the JavaScript programming language. It was released along with a whole slew of other new features on April 2nd this year as part of ECMAScript version 2020 (or ES2020).

This new operator is very similar to the logical OR (||) operator, with the exception that it only returns the right-hand side operand when the left-hand side operand evaluates to being nullish. This means that nullish coalescing returns the right-hand side operand when the left-hand side evaluates to undefined or null, but not false, 0, or "" as it will with the logical OR operator.

// These will return the left-hand side operand
// with nullish coalescing, but not OR
false || true // returns true
false ?? true // returns false
0 || true // returns true
0 ?? true // returns 0
"" || true // returns true
"" ?? true // returns ""
// These will return the right-hand side operand
// with nullish coalescing, same as OR
undefined || true // returns true
undefined ?? true // returns true
null || true // returns true
null ?? true // returns true

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

No responses yet

Write a response