Modern JavaScript code is full of short forms like const { name } = user and [...list, item]. These are destructuring, which unpacks values from arrays and objects into variables, and the spread and rest syntax, which both use three dots: spread expands a collection into pieces, and rest gathers pieces into a collection. Together they make code shorter and clearer, especially when you work with function options, API data and React-style state updates.
In this lesson you will learn
- Array destructuring: skipping, defaults, rest and swapping
- Object destructuring: renaming, defaults and nested values
- Spread for copying and merging arrays and objects
- Rest parameters for any number of arguments
- Named options with destructured parameters
This lesson goes deeper into the short introduction in JavaScript Objects. You should also know arrays.
Destructuring Arrays and Objects
"use strict";
// Array destructuring: take values by position
const marks = [92, 85, 78, 64];
const [first, second, ...others] = marks;
console.log(first, second, others);
const [, , third = 0, , fifth = "none"] = marks; // skip items, give defaults
console.log("third:", third, "fifth:", fifth);
let a = 1, b = 2;
[a, b] = [b, a]; // swap without a temp variable
console.log("swapped:", a, b);
// Object destructuring: take values by name
const student = { id: 7, name: "Tania", dept: "CSE", address: { city: "Sylhet", zip: "3100" } };
const { name, dept: department, cgpa = "N/A" } = student; // rename and default
console.log(name, department, cgpa);
const { address: { city } } = student; // nested
console.log("city:", city);
const { id, ...rest } = student; // everything except id
console.log("rest keys:", Object.keys(rest));
// Destructuring in loops
const scores = { Rina: 88, Arif: 74 };
for (const [person, score] of Object.entries(scores)) {
console.log(`${person} scored ${score}`);
}
Output
92 85 [ 78, 64 ]
third: 78 fifth: none
swapped: 2 1
Tania CSE N/A
city: Sylhet
rest keys: [ 'name', 'dept', 'address' ]
Rina scored 88
Arif scored 74
- Array destructuring works by position:
[first, second, ...others]takes the first two items, and...otherscollects the rest into a new array. - Empty places between commas skip items. A default after
=is used only when the value isundefined, as for the missing fifth mark. [a, b] = [b, a]swaps two variables in one line.- Object destructuring works by name.
dept: departmentreadsdeptinto a variable calleddepartment, andcgpa = "N/A"gives a default for a missing property. - Nested patterns follow the shape of the data:
{ address: { city } }reaches insideaddress. Note that this creates onlycity, not a variable calledaddress. { id, ...rest }puts every other property into a new object, a handy way to remove a key without changing the original.- Destructuring also works in loop headers:
for (const [person, score] of Object.entries(scores)).
Spread, Rest and Named Options
"use strict";
// Spread copies items out of arrays and objects
const cse = ["Rina", "Arif"], eee = ["Tania"];
const all = [...cse, ...eee, "Nabil"];
console.log(all, "max mark:", Math.max(...[71, 95, 88]));
const defaults = { theme: "light", fontSize: 16, lang: "en" };
const saved = { fontSize: 18, lang: "bn" };
const settings = { ...defaults, ...saved }; // later properties win
console.log(settings);
// Spread makes a SHALLOW copy
const original = { name: "Mitu", tags: ["js"] };
const copy = { ...original };
copy.name = "Copy";
copy.tags.push("css"); // the inner array is shared
console.log(original.name, original.tags);
// Rest parameters collect any number of arguments into an array
function total(label, ...amounts) {
const sum = amounts.reduce((s, x) => s + x, 0);
return `${label}: ${sum} (${amounts.length} items)`;
}
console.log(total("Books", 250, 180, 420));
// Destructuring parameters with defaults: named options
function createUser({ name, role = "student", active = true } = {}) {
return `${name} | ${role} | ${active ? "active" : "inactive"}`;
}
console.log(createUser({ name: "Sumon" }));
console.log(createUser({ name: "Dr. Karim", role: "teacher", active: false }));
Output
[ 'Rina', 'Arif', 'Tania', 'Nabil' ] max mark: 95
{ theme: 'light', fontSize: 18, lang: 'bn' }
Mitu [ 'js', 'css' ]
Books: 850 (3 items)
Sumon | student | active
Dr. Karim | teacher | inactive
[...cse, ...eee, "Nabil"]builds a new array from the items of others.Math.max(...array)spreads an array into separate arguments.{ ...defaults, ...saved }merges objects. When both have a key, the later one wins, which is the standard way to apply user settings over defaults.- Spread makes a shallow copy. Changing
copy.nameleft the original alone, buttagsis the same array in both objects, so pushing to it changed the original too. UsestructuredClone()for a deep copy. - In a function definition,
...amountsis a rest parameter: it gathers all remaining arguments into a real array. It must be the last parameter. - Destructuring a parameter,
{ name, role = "student" } = {}, gives a function named options with defaults. Callers pass only what they need, in any order. The final= {}allows calling it with no argument at all.
Three Dots: Spread or Rest?
| Where the dots appear | Name | What it does | Example |
|---|---|---|---|
| In an array or object literal | Spread | Expands items or properties | [...a, 4], {...obj} |
| In a function call | Spread | Expands an array into arguments | Math.max(...nums) |
| In a function’s parameter list | Rest | Collects arguments into an array | function f(...args) |
| In a destructuring pattern | Rest | Collects the remaining items or properties | const [x, ...more] = a |
Common Mistakes
- Destructuring
nullorundefined, which throws a TypeError. Provide a default such as= {}. - Expecting spread to deep-copy nested arrays and objects.
- Starting a line with
{when assigning to existing variables: write({ a, b } = obj);with parentheses. - Putting a rest element anywhere but last, such as
[...start, last], which is a syntax error.
Practice Exercises
Exercise 1. From const res = { data: { user: { name: "Rina", email: "r@example.com" } }, status: 200 }, get name and status in one statement.
Show answer
const { data: { user: { name } }, status } = res;
console.log(name, status); // Rina 200
Exercise 2. Write average(...nums) that returns the average of any number of arguments, or 0 if there are none.
Show answer
const average = (...nums) =>
nums.length ? nums.reduce((s, n) => s + n, 0) / nums.length : 0;
console.log(average(80, 90, 100), average()); // 90 0
Frequently Asked Questions
Is spread the same as Object.assign?
For copying and merging into a new object they give the same result: { ...a, ...b } equals Object.assign({}, a, b). Object.assign can also change an existing target object, while spread always creates a new one.
Is rest the same as the arguments object?
Rest parameters replace the old arguments object. Rest gives a real array with methods like map, works in arrow functions, and only includes the arguments you did not name.
Summary
- Destructuring unpacks arrays by position and objects by name.
- Defaults, renaming, nesting and rest elements make patterns flexible.
- Spread copies and merges, but only shallowly.
- Rest parameters and destructured options make flexible function signatures.
Next: JSON in JavaScript.
