Reading history

JavaScript Destructuring, Spread and Rest Syntax

6 min read 0 views

Learn array and object destructuring with defaults, renaming and nesting, spread for copying and merging, rest parameters and named function options.

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 ...others collects the rest into a new array.
  • Empty places between commas skip items. A default after = is used only when the value is undefined, as for the missing fifth mark.
  • [a, b] = [b, a] swaps two variables in one line.
  • Object destructuring works by name. dept: department reads dept into a variable called department, and cgpa = "N/A" gives a default for a missing property.
  • Nested patterns follow the shape of the data: { address: { city } } reaches inside address. Note that this creates only city, not a variable called address.
  • { 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.name left the original alone, but tags is the same array in both objects, so pushing to it changed the original too. Use structuredClone() for a deep copy.
  • In a function definition, ...amounts is 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 appearNameWhat it doesExample
In an array or object literalSpreadExpands items or properties[...a, 4], {...obj}
In a function callSpreadExpands an array into argumentsMath.max(...nums)
In a function’s parameter listRestCollects arguments into an arrayfunction f(...args)
In a destructuring patternRestCollects the remaining items or propertiesconst [x, ...more] = a

Common Mistakes

  1. Destructuring null or undefined, which throws a TypeError. Provide a default such as = {}.
  2. Expecting spread to deep-copy nested arrays and objects.
  3. Starting a line with { when assigning to existing variables: write ({ a, b } = obj); with parentheses.
  4. 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.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *