Destructuring Deluxe

Grade 13, page 4 of 12. A one-minute read.

You learned the basics of destructuring in Grade 8. Here are some more tricks.

Swapping two variables

Remember the juice-and-milk swap puzzle from Grade 1, where we needed a third cup? With array destructuring, you can swap in one line, no extra cup needed:

JavaScript
let left = "juice";
let right = "milk";

[left, right] = [right, left];

console.log(left, right);

It prints

milk juice

Nested destructuring

You can reach into nested objects and arrays in one go:

JavaScript
const order = {
  id: 1042,
  customer: { name: "Aisha", phone: "024-000-0000" },
  items: ["waffle", "fried fish", "salsa"],
};

const {
  customer: { name },
  items: [firstItem],
} = order;

console.log(name);
console.log(firstItem);

It prints

Aisha
waffle

(Use this one sparingly. Deeply nested destructuring can be harder to read than just writing order.customer.name.)

Destructuring in loops

Combined with Object.entries (Grade 8), destructuring makes looping over objects beautiful:

JavaScript
const prices = { burger: 45, omelet: 30, pancakes: 15 };

for (const [dish, price] of Object.entries(prices)) {
  console.log(`${dish}: $${price}`);
}

It prints

burger: $45
omelet: $30
pancakes: $15

Each entry is a [key, value] pair, and [dish, price] unpacks it into two nicely named variables.

Returning multiple values

A function can only return one thing. But that one thing can be an object or an array, which you can immediately destructure:

JavaScript
function getStats(numbers) {
  const min = Math.min(...numbers);
  const max = Math.max(...numbers);
  const average = numbers.reduce((a, b) => a + b, 0) / numbers.length;
  return { min, max, average };
}

const { min, max, average } = getStats([4, 8, 15, 16, 23, 42]);
console.log(`min ${min}, max ${max}, average ${average}`);

It prints

min 4, max 42, average 18

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning