Unpacking parcels
Object and array destructuring, default parameters, rest and spread.
parcel.to, parcel.weight, parcel.city… By lunch my paw was sore. Turns out a parcel can be unpacked in one move.const parcel = { to: "Mittens", city: "London", weight: 2 };
const { to, weight } = parcel;
console.log(to);
console.log(weight);const to = parcel.to; const weight = parcel.weight;.This is object destructuring. The rules:
- on the left of
=, inside curly braces, go key names; you get variables with the same names; - order doesn't matter: keys are looked up by name;
- a missing key gives undefined;
- to rename:
{ to: recipient }means "taketo, put it intorecipient"; - a default value:
{ express = false }kicks in when the field is missing.
const parcel = { to: "Mittens", weight: 2 };
const { to: recipient, express = false } = parcel;
console.log(recipient);
console.log(express);= supplies a fallback.Arrays unpack by position, not by name: const [first, second] = queue. Skip a position with an empty comma: const [, second] = queue. The same trick swaps two variables — no temporary third one needed.
const queue = ["Mittens", "Oscar", "Fluffy"];
const [first, , third] = queue;
console.log(first, third);
let left = "parcel";
let right = "letter";
[left, right] = [right, left];
console.log(left, right);The most useful place for destructuring is function parameters. Instead of five arguments whose order nobody remembers, the function takes one "form" object and unpacks it right away. Field order no longer matters at the call site, and missing fields get defaults.
function stamp({ to, weight, express = false }) {
const speed = express ? "express" : "standard";
return `${to}: ${weight} kg, ${speed}`;
}
console.log(stamp({ weight: 2, to: "Mittens" }));
console.log(stamp({ to: "Oscar", weight: 5, express: true }));A plain parameter can have a default too: function price(weight, rate = 100). If the argument is left out, the parameter would be undefined — now it gets 100 instead.
And what if you don't know how many arguments will come? That's what a rest parameter ...weights is for: it gathers all remaining arguments into a real array.
function price(weight, rate = 100) {
return weight * rate;
}
console.log(price(3));
console.log(price(3, 150));
function totalWeight(...weights) {
let sum = 0;
for (const w of weights) sum += w;
return sum;
}
console.log(totalWeight(2, 3));
console.log(totalWeight(1, 1, 1, 4));
console.log(totalWeight());The same three dots also work the other way — that's spread. Rest gathers many values into one array; spread scatters an array or object back into pieces:
Math.max(...weights)turns an array into separate arguments;[...morning, ...evening]makes one new array out of two;{ ...defaults, express: true }copies an object with one field changed. When keys clash, whatever comes later wins.
const weights = [2, 7, 4];
console.log(Math.max(...weights));
const morning = ["Mittens"];
const evening = ["Oscar", "Fluffy"];
console.log([...morning, ...evening]);
const defaults = { wrap: "box", express: false };
console.log({ ...defaults, express: true });Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.