CodeOath
← All posts
JavaScript65 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Contents — Part 9 of 16: Destructuring
Part 9 of 16 · ~1 min

Destructuring

Destructuring pulls values out of arrays/objects into named variables directly, and it's used constantly beyond simple variable assignment.

const [first, second] = [10, 20]; // first = 10, second = 20
const [, , third] = [10, 20, 30]; // skip positions with empty commas — third = 30
const [head, ...tail] = [1, 2, 3, 4]; // head = 1, tail = [2, 3, 4] — rest works here too

const { name, age } = { name: "Alice", age: 30 }; // name = "Alice", age = 30
const { name: userName } = { name: "Alice" }; // rename while destructuring — userName = "Alice"
const { role = "guest" } = {}; // default value when the key is missing — role = "guest"

function greet({ name, role = "guest" } = {}) { // destructure a parameter, with a default for the WHOLE object too
  console.log(`Hello, ${name}, you are a ${role}`);
}
greet({ name: "Sam" }); // "Hello, Sam, you are a guest"
greet(); // works because of `= {}` — without it, destructuring `undefined` throws a TypeError

The = {} default on the parameter itself (not just on individual properties) matters specifically for the case where the function is called with no argument at all — without it, JavaScript tries to destructure undefined and throws immediately, before any of the inner defaults get a chance to apply.

Destructuring also works in for...of loops, which is exactly why Object.entries() pairs so well with it:

for (const [key, value] of Object.entries({ a: 1, b: 2 })) {
  console.log(key, value); // "a" 1, then "b" 2
}