Destructuring

Destructuring is a way of teasing apart collections and assigning the component values to variables.

Table of Contents

  1. Destructuring Arrays
  2. Destructuring Function Return Values
  3. Destructuring Objects
  4. Destructuring Nested Data
  5. Complex Nested Data

Destructuring Arrays

Instead of indexed array assignment:

const hearts = ["πŸ–€", "❀️", "πŸ’›"];

const black = hearts[0];
const red = hearts[1];
const yellow = hearts[2];

console.log(yellow); // πŸ’›

With destructuring syntax we can write:

const hearts = ["πŸ–€", "❀️", "πŸ’›"];

const [black, red, yellow] = hearts;

console.log(yellow); // πŸ’›

Destructuring Function Return Values

Let’s say you a function named weather that returns an array of three temperatures.

const temperatures = weather(); // [10, 15, 22]

And you know that the forecasted low, high, and average temperature appear in that order in the array.

You can destructure the returned array into the variables low, high, and average:

const [low, high, average] = weather(); // [10, 15, 22]

console.log(`Average: ${average} Low: ${low} High: ${high} `);

// Average: 22 Low: 10 High: 15

Destructuring Objects

We can also promote object keys to variables using destructuring:

const adventures = { mountain: "⛰️", desert: "🏜️" };
const { mountain, desert } = adventures;

console.log(mountain); // ⛰️
console.log(desert); // 🏜️

We can also name the variables sometime different from the object keys:

const { mountain: everest, desert: sahara } = adventures;

console.log(sahara); // 🏜️
console.log(everest); // ⛰️

Destructuring Nested Data

Destructuring can also be used to pluck data out of nested data structures, like an array of objects:

const animalFriends = [
  { name: "Monkey", emoji: "πŸ’" },
  { name: "Dog", emoji: "πŸ•" },
  { name: "Cow", emoji: "πŸ„" },
];

// - Skip the zeroth position in the array with a comma.
// - Grab the emoji out of the object at first position.
// - Skip the object in the final position of the array.
const [, { emoji: dogEmoji }] = animalsFriends;

console.log(dogEmoji); // πŸ•

Complex Nested Data

This example from the MDN shows the destructuring of the kind of object you might get back from an API:

// Let's pretend this data came from an API.
const apiResponse = {
  title: "JS Environment",
  translations: [
    {
      locale: "de - Germany",
      last_edit: "2014-04-14T08:43:37",
      title: "JS Umgebung",
    },
  ],
};

// Pluck the English and German title from the data.
let {
  title: englishTitle,
  translations: [{ title: localeTitle }],
} = apiResponse;

console.log(englishTitle); // "JS Environment"
console.log(localeTitle); // "JS Umgebung"

Resources