How to have a destructuring assignment with a default value?

Learn JS: Destructuring Lesson 2.

I'm assuming you've read the previous lesson Destructuring 1 — Accessing object properties

Let's use a simple object in the examples:

const ages = {
robot: 23,
person: 33,
dog: 1

Assignment #

It turns out we can use destructuring to assign values to multiple variables at the same time. The only quirk is that {} in destructuring can indicate a block. To make sure JS knows what we want to do, we have to wrap it in additional () brackets.

let robot = 0;
let person = 0;

({robot, person} = ages);
// robot -> 23
// person -> 33

I would encourage you to use destructuring with consts, but there might be the case when it will help you make your code a lot cleaner. Use sparingly.

Default value #

What will happen if the property we're destructuring doesn't exist? Let's check:

const { ghost } = ages;
// ghost -> undefined

You can check for undefined and throw an Error, or if you want to build robust applications, you can implement the Postel's law.

"Be conservative in what you send, be liberal in what you accept."
robustness principle (Postel's law)

The easiest way to make your code more robust is to set a default value. Let's assume that ghost have 100 years.

const { ghost = 100 } = ages;
// ghost -> 100

Default values are used a lot, especially in the configuration options pattern. When exposing a complex functionality, you want to set as many default values as possible to make your function easier to use.

In practice, it's common to see destructuring of multiple constants at the same time:

const { 
ghost = 100,
robot = 0,
person = 18 } = ages;
// ghost -> 100,
// robot -> 23
// person -> 33

Next Lesson

(Previous Lesson)

Share on Hacker News
Share on LinkedIn

← Home