DEV Community

Cover image for πŸš€ Nullish Coalescing Operator | ES2020
Niall Maher
Niall Maher

Posted on

12 2

πŸš€ Nullish Coalescing Operator | ES2020

The ES2020 was just approved by the TC39 committee, and in the proposal, Nullish Coalescing is a thing. What is "Optional chaining"?

Well, it's another way to assign fallback values other than using the OR operators we might normally use.

This video goes over an example to hopefully make more sense of it. πŸ€“
In this example, we will provide default values but keep values other than null or undefined. If you want more information, scroll down. πŸ‘‡

The Nullish Coalescing Operator returns the results of the right-hand-side expression if the left-hand-side expression is either null or undefined.

If that sounds confusing, don't worry it's actually really simple.

There is often use cases where falsy values could be a wanted default like the number zero or an empty string. Using the Nullish Coalescing Operator makes it easy to check only for null and undefined before falling through the OR evaluation. I think the example below will make it a little less complicated sounding.

Using the nullish coalescing operator versus OR operator.

### Using the OR Operator.

// example based on MDN docs.
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;

const valA = nullValue || "default for A";
const valB = emptyText || "default for B";
const valC = someNumber || 0;

console.log(valA); // "default for A"
console.log(valB); // "default for B" (as the empty string is falsy)
console.log(valC); // 42
Enter fullscreen mode Exit fullscreen mode

Using the Nullish Coalescing Operator

// example from MDN
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;

const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;

console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
Enter fullscreen mode Exit fullscreen mode

So as you can see, nothing too crazy. Just another tool to add to your JavaScript belt.


Follow me on Twitter

Subscribe on CodΓΊ Community

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more