Lesson 20 of 28
In progress
Destructuring and spread
Unpack objects and arrays with defaults, rename variables, and copy or merge data without mutating the original.
Destructuring takes a value apart; spread puts values together. Together they replace a lot of temporary variables and a lot of accidental mutation.
What you will learn
- Destructure objects and arrays, with defaults and renaming.
- Collect the rest of the values with
.... - Copy and merge data without changing the original.
Object destructuring
Editable. Runs in your browser.
const { city: town, country = "India" } = user;
console.log(name, role, town, country);
Press Run to see the output.
The braces match property names. city: town renames the variable while reading the city property. country = "India" supplies a default when the property is missing or undefined.
Defaults apply only for undefined, not for null. A property explicitly set to null keeps null, which is usually correct.
Array destructuring
Editable. Runs in your browser.
console.log(first, second, third);
const [head = 0, …rest] = [];
console.log(head, rest);
Press Run to see the output.
Array destructuring matches by position. An empty slot with a comma skips a value. The rest element collects everything remaining into a real array.
Swapping variables becomes a one-liner:
Editable. Runs in your browser.
Press Run to see the output.
Destructuring in parameters
Editable. Runs in your browser.
console.log(describe({ name: "Ana" }));
console.log(describe({ name: "Ravi", role: "tutor" }));
Press Run to see the output.
This is common for options objects, because the call site names each value. It also documents which fields the function uses, right in the signature.
Passing undefined as the argument throws, since the parameter cannot be destructured. Give the whole object a default when it may be omitted: function describe({ name } = {}).
Spread
Editable. Runs in your browser.
const first = [1, 2];
const second = [3, 4];
const all = […first, …second];
console.log(custom);
console.log(all);
Press Run to see the output.
Spread into an object copies enumerable own properties. Later keys win, which is why the override goes after the spread. Spread into an array concatenates values.
Spread also works in calls: Math.max(...numbers) instead of apply. For very large arrays, a loop avoids the argument limit, but that is rarely a practical concern.
Rest in destructuring
Editable. Runs in your browser.
console.log(publicUser);
Press Run to see the output.
Rest is the standard way to omit fields when preparing data for output. It is shallow, so nested secrets are not removed; strip those explicitly.
Editable. Runs in your browser.
console.log(total(10, 20, 30));
Press Run to see the output.
Rest parameters and spread look the same and do opposite jobs: rest collects, spread expands.
Destructuring in loops
Editable. Runs in your browser.
for (const { name, score } of rows) {
console.log(`${name}: ${score}`);
}
const pairs = Object.entries({ a: 1, b: 2 });
for (const [key, value] of pairs) {
console.log(key, value);
}
Press Run to see the output.
Destructuring in the loop head removes two lines per iteration and names exactly the fields being used. The same works in map and filter callbacks when an object has many fields and only one matters.
Spread in calls and copies
Editable. Runs in your browser.
const merged = { …{ a: 1 }, …{ b: 2, a: 3 } };
console.log(merged);
Press Run to see the output.
Math.max takes separate arguments, not an array, so spread converts one to the other. In the merge, the later a wins, which is the rule to remember for every object spread.
Nested patterns
Editable. Runs in your browser.
const {
customer: { name, address: { city } },
lines: [{ sku }]
} = order;
console.log(name, city, sku);
Press Run to see the output.
Nested destructuring reads top to bottom and names only the leaves you need. It is concise, and it becomes hard to follow beyond two levels; at that point, destructure the outer object first and then the inner one on its own line.
A default on a nested pattern applies only when the whole nested object is undefined. If the object exists but the leaf is missing, put the default on the leaf instead, as the example does for city. That distinction matters when an API sends an empty object rather than omitting the field entirely.
Copies are shallow
Editable. Runs in your browser.
console.log(original.tags);
Press Run to see the output.
The copy has its own tags property, but both point at the same array, so the original changes. For nested updates, spread each level:
Editable. Runs in your browser.
console.log(original.tags, updated.tags);
Press Run to see the output.
That pattern — copy the path you change, reuse the rest — is what immutable updates mean in practice, and it is what state management libraries expect.
[...obj] does not copy an object; arrays and objects need different spread targets. Spreading a non-iterable object into an array throws TypeError: obj is not iterable. Use { ...obj } for objects.
Given a response object with data and meta, destructure the first item of data with defaults for title and done, and build a new object with the meta plus an updated count. Do not mutate the response.
Show solution
Editable. Runs in your browser.
const [{ title = "Untitled", done = false }] = response.data;
const updated = {
data: [{ title, done: true }],
meta: { …response.meta, count: response.data.length }
};
console.log(updated);
console.log(response.data[0].done);
Press Run to see the output.
Destructuring pulls the fields with defaults, and spread copies the meta before adding a count. The original object is untouched, which the last line confirms.
Recap
- Destructure by name for objects, by position for arrays, with defaults and renaming.
- Rest collects, spread expands; later keys override earlier ones.
- Spread copies one level, so nested updates need an explicit copy per level.
Next, you will use the array methods that replace most manual loops.
Can I destructure a function's return value?
Does spread copy getters?
Progress is saved in this browser only. No account, no email.