JavaScript course menu
JavaScript Destructuring and the Spread Operator
Learn JavaScript destructuring and spread: unpacking arrays and objects into variables, default values, renaming, nested destructuring, rest elements, swapping variables, destructuring function parameters, and spreading arrays and objects to copy and merge.
On this page
Destructuring unpacks values from arrays or properties from objects into separate variables in one line. Spread (...) does the reverse: it expands an array or object into another. Both are used constantly in modern JavaScript and frameworks such as React.
Array destructuring#
Variables are matched by position:
const rgb = [47, 95, 224];
const [red, green, blue] = rgb;
console.log(red, green, blue);
const [first, , third] = ["a", "b", "c"]; // skip with an empty slot
console.log(first, third);
const [x = 0, y = 0, z = 0] = [5, 7]; // defaults for missing items
console.log(x, y, z);47 95 224
a c
5 7 0Rest elements#
...name collects the remaining items into an array:
const [winner, ...others] = ["Asha", "Ravi", "Meera", "Kiran"];
console.log(winner);
console.log(others);Asha
[ 'Ravi', 'Meera', 'Kiran' ]Swapping variables#
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);2 1Object destructuring#
Variables are matched by property name, so order does not matter:
const user = { name: "Asha", age: 21, city: "Pune" };
const { name, city } = user;
console.log(name, city);Asha PuneRenaming and defaults#
const user = { name: "Asha", city: "Pune" };
const { name: fullName, country = "India", city: town } = user;
console.log(fullName, country, town);Asha India Punename: fullNamereadsnameinto a variable calledfullName.country = "India"is used becausecountryis missing.
Rest properties#
const product = { id: 7, name: "Pen", price: 20, stock: 140 };
const { id, ...details } = product;
console.log(id);
console.log(details);7
{ name: 'Pen', price: 20, stock: 140 }This is a neat way to remove a property without changing the original object.
Nested destructuring#
const order = {
id: 1042,
customer: { name: "Ravi", address: { city: "Chennai" } },
items: [{ title: "Notebook" }, { title: "Pen" }],
};
const {
customer: {
name,
address: { city },
},
items: [firstItem],
} = order;
console.log(name, city, firstItem.title);Ravi Chennai NotebookKeep nesting shallow for readability; two levels is usually plenty.
Destructuring in function parameters#
Destructuring is common in parameter lists, especially for options objects and React components:
function formatUser({ name, age, city = "Unknown" }) {
return `${name}, ${age}, ${city}`;
}
console.log(formatUser({ name: "Meera", age: 28 }));
const points = [[1, 2], [3, 4]];
for (const [x, y] of points) {
console.log(`x=${x} y=${y}`);
}Meera, 28, Unknown
x=1 y=2
x=3 y=4Spreading arrays#
const morning = ["tea", "toast"];
const evening = ["snacks"];
const allDay = [...morning, "lunch", ...evening];
const copy = [...morning];
console.log(allDay);
console.log(copy === morning);
console.log(Math.max(...[4, 19, 7]));[ 'tea', 'toast', 'lunch', 'snacks' ]
false
19Spreading objects#
Spread copies an object's properties into a new object. When keys repeat, later ones win:
const defaults = { theme: "light", fontSize: 16, language: "en" };
const saved = { theme: "dark" };
const settings = { ...defaults, ...saved };
console.log(settings);
const user = { name: "Asha", city: "Pune" };
const moved = { ...user, city: "Delhi" };
console.log(user.city, moved.city);{ theme: 'dark', fontSize: 16, language: 'en' }
Pune Delhi{ ...object, key: newValue } creates an updated copy without changing the original, a pattern used everywhere in React state updates.
Remember that spread copies are shallow: nested objects are still shared (Objects).
Spread versus rest#
The same ... syntax does two opposite things depending on where it appears:
Practice#
Practice exercise
Given const response = { status: 200, data: { user: { id: 5, name: "Kiran", roles: ["admin", "editor"] } } }, use one destructuring statement to get status, the user's name, and their first role as mainRole. Then create an updated copy of the user with name: "Kiran Rao" without changing the original.
Show solution
const response = {
status: 200,
data: { user: { id: 5, name: "Kiran", roles: ["admin", "editor"] } },
};
const {
status,
data: {
user: {
name,
roles: [mainRole],
},
},
} = response;
console.log(status, name, mainRole);
const updatedUser = { ...response.data.user, name: "Kiran Rao" };
console.log(updatedUser.name, response.data.user.name);200 Kiran admin
Kiran Rao KiranKey takeaway#
Finished this lesson?