typestar

Destructuring in JavaScript

Pulling values out of objects and arrays by shape.

const user = { id: 7, name: "ada", city: "london" };
const { name, city: town, country = "uk" } = user;

const colors = ["red", "green", "blue"];
const [first, ...rest] = colors;

function describe({ id, name }) {
  return `#${id} ${name}`;
}

const label = describe(user);
const swapped = [colors[1], colors[0]];

How it works

  1. Object patterns can rename and supply defaults.
  2. ...rest collects whatever the pattern didn't name.
  3. A parameter can be destructured in the signature.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
311
Tokens
98
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 65 seconds.

Type this snippet

Step 2 of 3 in Functions, step 15 of 43 in Language basics.

← Previous Next →

Destructuring in other languages