Destructuring and Spread
Destructuring is a syntax for unpacking values from arrays, or properties from objects, into separate variables in one statement: const [first, second] = list; or const { name, grade } = student;. Spread syntax (...) does the opposite: it expands an array or object into individual elements or properties, to copy, merge or pass them as arguments. Both arrived in ES2015 and appear on nearly every page of modern JavaScript.
In One Minute
- Array destructuring works by position:
const [a, b] = [1, 2];. - Object destructuring works by name:
const { name, grade } = student;. - Add defaults (
= value), rename (name: studentName), skip ([, second]) and collect the rest (...others). - Spread copies and merges:
[...a, ...b],{ ...defaults, ...settings },fn(...args). - Spread copies are shallow: nested objects are still shared.
Array Destructuring
Syntax
const [first, second, ...rest] = array;Example
const fees = [120, 85, 45, 200];
const [first, second] = fees;
console.log(first, second);
const [, , third] = fees;
console.log(third);
const [head, ...rest] = fees;
console.log(head, rest);
const [a, b, c, d, e = 0] = fees;
console.log(e);120 85
45
120 [85, 45, 200]
0Explanation: variables are filled in order. Empty commas skip positions. ...rest collects everything left into a new array (it must come last). A default (e = 0) is used when the value at that position is undefined, including when the array is too short.
Swapping Variables
Destructuring swaps two variables without a temporary one:
let low = 450;
let high = 120;
[low, high] = [high, low];
console.log(low, high);120 450Destructuring Function Results
A function can return several values in an array, and the caller destructures them. This is common for "pairs" such as a value and an error, or Object.entries items:
function splitName(full) {
const [first, ...others] = full.trim().split(" ");
return [first, others.join(" ")];
}
const [firstName, lastName] = splitName("Srihitha Anamaneni");
console.log(firstName, "|", lastName);
for (const [grade, fee] of Object.entries({ 9: 400, 10: 415 })) {
console.log(grade, fee);
}Srihitha | Anamaneni
9 400
10 415Object Destructuring
Syntax
const { prop1, prop2: newName, prop3 = defaultValue, ...others } = object;Example
const student = { name: "Advitha", grade: 9, city: "San Francisco", balance: 45 };
const { name, grade } = student;
console.log(name, grade);
const { city: hometown } = student;
console.log(hometown);
const { scholarship = "none" } = student;
console.log(scholarship);
const { balance, ...profile } = student;
console.log(balance, profile);Advitha 9
San Francisco
none
45 { name: 'Advitha', grade: 9, city: 'San Francisco' }| Pattern | Meaning |
|---|---|
{ name } | Take name into a variable called name |
{ city: hometown } | Take city into a variable called hometown |
{ scholarship = "none" } | Use "none" if the property is missing or undefined |
{ city: home = "Dallas" } | Rename and default |
{ balance, ...profile } | Take balance; put every other property into profile |
Nested Destructuring
Patterns can go deep, matching the shape of the data:
const payment = {
id: 7,
student: { name: "Navika", contact: { city: "Dallas" } },
amounts: [120, 60],
};
const {
student: { name, contact: { city } },
amounts: [firstAmount],
} = payment;
console.log(name, city, firstAmount);Navika Dallas 120Note that student and contact here are only paths, not variables. Destructuring a missing nested object throws: if payment.student were undefined, reading { name } from it would fail. Add a default for the intermediate level (student: { name } = {}) or use optional chaining instead.
In Function Parameters
Destructuring in the parameter list is how most modern functions accept options:
function receipt({ name, amount, currency = "USD" }) {
return `${name}: ${amount} ${currency}`;
}
console.log(receipt({ name: "Srihitha", amount: 85 }));
const totals = [["Navika", 180], ["Advitha", 245]];
console.log(totals.map(([who, total]) => `${who}=${total}`).join(", "));Srihitha: 85 USD
Navika=180, Advitha=245Spread Syntax
Spread syntax ... expands an iterable (array, string, Set, Map) into individual elements, or an object into its own properties.
Spreading Arrays
const fall = [120, 85];
const spring = [45, 200];
const all = [...fall, ...spring];
const withExtra = [10, ...fall, 99];
const copy = [...fall];
copy.push(1);
console.log(all, withExtra);
console.log(fall, copy);
console.log(Math.max(...all));
console.log([..."Fee"], [...new Set([1, 1, 2])]);[120, 85, 45, 200] [10, 120, 85, 99]
[120, 85] [120, 85, 1]
200
['F', 'e', 'e'] [1, 2]Spreading Objects
Object spread copies an object's own enumerable properties into a new object literal. Later properties win, which makes it perfect for defaults and updates:
const defaults = { currency: "USD", pageSize: 25, theme: "light" };
const saved = { pageSize: 50, theme: "dark" };
const settings = { ...defaults, ...saved };
console.log(settings);
const student = { name: "Navika", balance: 120 };
const afterPayment = { ...student, balance: student.balance - 50 };
console.log(student, afterPayment);{ currency: 'USD', pageSize: 50, theme: 'dark' }
{ name: 'Navika', balance: 120 } { name: 'Navika', balance: 70 }The second example is the standard immutable update: a new object with one property changed, the original untouched.
Rest vs Spread
The same three dots mean opposite things depending on where they appear:
| Position | Name | What it does | Example |
|---|---|---|---|
| In a destructuring pattern or parameter list | Rest | Collects many values into one array or object | const [a, ...others] = list |
| In an array literal, object literal or call | Spread | Expands one value into many | [...list, 4], fn(...args) |
Spread Copies Are Shallow
Spread copies the top level only. Nested objects and arrays are shared between the original and the copy:
const original = { name: "Advitha", payments: [45] };
const copy = { ...original };
copy.name = "Changed";
copy.payments.push(200);
console.log(original.name, original.payments);
console.log(copy.payments === original.payments);
const deep = structuredClone(original);
deep.payments.push(999);
console.log(original.payments, deep.payments);Advitha [45, 200]
true
[45, 200] [45, 200, 999]Explanation: changing copy.name didn't affect the original, because name is a primitive that was copied. But copy.payments is the same array as original.payments, so pushing to it changed both. structuredClone makes a deep copy, cloning nested objects too. The lesson on copying objects covers this fully.
In Practice
The Fee Tracker updates one payment inside a student record without changing the original, using destructuring to read and spread to write:
const record = {
name: "Srihitha",
contact: { city: "San Francisco", phone: "4155550100" },
payments: [{ id: 1, amount: 200 }, { id: 2, amount: 150 }],
};
function correctPayment(rec, id, amount) {
const { payments, ...rest } = rec;
return {
...rest,
payments: payments.map((p) => (p.id === id ? { ...p, amount } : p)),
};
}
const fixed = correctPayment(record, 2, 175);
console.log(fixed.payments);
console.log(record.payments[1].amount);
console.log(fixed.contact === record.contact);[{ id: 1, amount: 200 }, { id: 2, amount: 175 }]
150
trueThe original is untouched, the changed payment is a new object, and unchanged parts (like contact) are shared, which is safe as long as nobody changes them in place.
Common Mistakes
Destructuring undefined or null. const { name } = undefined throws TypeError. Give a default: const { name } = student ?? {};.
Starting a line with { for assignment destructuring. { a, b } = obj; is read as a block. Wrap it: ({ a, b } = obj);.
Expecting spread to deep-copy. Nested objects stay shared. Use structuredClone or spread each level.
Expecting defaults to replace null. Destructuring defaults, like parameter defaults, apply only to undefined.
Interview Corner
How do you swap two variables without a temporary variable?
[a, b] = [b, a];. The right side builds a temporary array, and array destructuring assigns its items back in swapped order.
Is object spread a deep copy?
No. { ...obj } copies own enumerable properties one level deep; nested objects are copied by reference. For a deep copy of plain data, use structuredClone(obj).
What is the difference between rest and spread?
Same ... syntax, opposite roles. Rest appears in binding patterns and parameter lists and collects remaining elements into an array (or remaining properties into an object). Spread appears in array literals, object literals and calls and expands an iterable or object into individual elements, properties or arguments.
Practice
Challenge: Write applySettings(saved) that merges saved over defaults { currency: "USD", pageSize: 25, notify: { email: true, sms: false } }, merging the nested notify object too, so that applySettings({ notify: { sms: true } }) keeps email: true.
Show solution
const DEFAULTS = { currency: "USD", pageSize: 25, notify: { email: true, sms: false } };
function applySettings(saved = {}) {
return {
...DEFAULTS,
...saved,
notify: { ...DEFAULTS.notify, ...saved.notify },
};
}
console.log(applySettings({ notify: { sms: true } }));
console.log(applySettings({ pageSize: 50 }));{ currency: 'USD', pageSize: 25, notify: { email: true, sms: true } }
{ currency: 'USD', pageSize: 50, notify: { email: true, sms: false } }Key Takeaways
| Task | Code |
|---|---|
| First two items | const [a, b] = arr; |
| Swap | [a, b] = [b, a]; |
| Property with default | const { x = 0 } = obj; |
| Rename | const { city: home } = obj; |
| Copy and change | { ...obj, balance: 0 } |
| Merge arrays | [...a, ...b] |
Was this tutorial helpful?