JavaScript Destructuring and Spread
JavaScript destructuring is a short syntax for pulling values out of arrays and objects into variables. Together with the spread operator (...), it is everywhere in modern code, from function parameters to React components.
Array Destructuring
Variables are matched by position. Skip items with an empty slot, and collect the rest with ...rest.
const rgb = [255, 128, 0];
const [red, green, blue] = rgb;
console.log(red, green, blue);
const [first, , third] = ["a", "b", "c"];
console.log(first, third);
const [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail.join(","));255 128 0 a c 1 2,3,4
Object Destructuring
Variables are matched by property name. You can rename with a colon and give defaults with =.
const order = { id: 101, total: 49.5, status: undefined };
const { id, total: amount, status = "pending", note = "none" } = order;
console.log(id, amount, status, note);101 49.5 pending none
Destructuring in Function Parameters
Destructuring a parameter gives you named options with defaults, which is clearer than a long list of positional arguments.
function createUser({ name, role = "viewer", active = true }) {
return `${name} (${role}) ${active ? "active" : "disabled"}`;
}
console.log(createUser({ name: "Asad" }));
console.log(createUser({ name: "Mehwish", role: "admin" }));Asad (viewer) active Mehwish (admin) active
Swapping Variables
let a = "left", b = "right";
[a, b] = [b, a];
console.log(a, b);right left
The Spread Operator
Spread expands an array or object in place. Use it to copy, merge, or pass array items as separate arguments. When merging objects, later properties win.
const defaults = { theme: "light", lang: "en" };
const saved = { theme: "dark" };
const settings = { ...defaults, ...saved };
console.log(settings);
const nums = [4, 9, 2];
console.log(Math.max(...nums));{
"theme": "dark",
"lang": "en"
}
9Spread vs Rest
- Spread (...x) on the right side or in a call expands values out
- Rest (...x) on the left side or in parameters gathers values in
- Both copy only one level deep (shallow)
Frequently asked questions
What is the difference between spread and rest in JavaScript?
They use the same three dots. Spread expands an iterable or object into individual elements; rest collects multiple elements into a single array or object.
How do I set a default value when destructuring?
Use = after the name: const { size = "M" } = options. The default applies only when the value is undefined.
Does the spread operator deep copy objects?
No. It makes a shallow copy. Nested objects are still shared; use structuredClone for a deep copy.