← Today I Learned

Nullish coalescing operator (??)

Check for null values faster than you can say "??".

  • development
  • javascript
  • nullish
  • react
  • workflow
Published

Sep 20, 2020 @ 7:52 AM

Overview

Summary

A nullish value in Javascript is a value that is either null or undefiend. The nullish coalescing operator (??) is a Binary logical operator.

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. | Source

Usage

A good example of when to use this operator is when you are working with localStorage. If you try to get an item that doesn't exist, the Storage interface will return null. | Source

useEffect(() => {
  const storage = localStorage.getItem("dark-theme-key");
  const initialState = JSON.parse(storage ?? "true");
  const [darkTheme, setDarkTheme] = useState(initialState);
}, []);

You can learn more about useEffect here.

Example

If the left side of the ?? operator is null or undefined, the right side is returned. Otherwise the left side is returned.

const name1 = null ?? "Bob";
const name2 = undefined ?? "Burger";
const name3 = "Jeff" ?? "Britta";

console.log({ name1, name2, name3 });

Th output is the following:

{ name1: "Bob", name2: "Burger", name3: "Jeff" }

Resources

All rights reserved 2022