01 / 21

Destructuring &
Spread/Rest

Learn to unpack values from objects and arrays, and use the three-dot syntax to collect or expand data with elegance.

JavaScript

What is Destructuring?

Destructuring is a syntax that lets you extract individual values from objects or arrays and assign them to variables: all in a single, concise statement.

Source Object name : "Ada" age : 36 role : "dev" name = "Ada" age = 36 role = "dev" Individual Variables

Why Destructuring Matters

Cleaner Code
Replace repetitive dot-notation lookups with a single line.
Readable APIs
Function parameters clearly show which properties are expected.
Fewer Bugs
Default values catch missing data before it causes errors.

Two Flavors: Object vs Array

{ } Object Destructuring
Matches by property name. Order does not matter.
[ ] Array Destructuring
Matches by position (index). Names are up to you.
JS
// Object: match by name
const { name, age } = person;

// Array: match by position
const [first, second] = colors;

Object Destructuring Syntax

JS
const user = {
  name: "Ada",
  age: 36,
  role: "engineer"
};

// Pull out name and role
const { name, role } = user;

console.log(name);  // "Ada"
console.log(role);  // "engineer"

Renaming & Defaults

JS
const config = { host: "localhost", port: 3000 };

// Rename: host → hostname
const { host: hostname } = config;
console.log(hostname); // "localhost"

// Default value if property is missing
const { port, debug = false } = config;
console.log(debug);    // false (default)
Renaming
Use key: newName to assign the value to a different variable name.
Defaults
Use key = value to provide a fallback when the property is undefined.

Array Destructuring

JS
const colors = ["red", "green", "blue"];

// Pull by position
const [primary, secondary] = colors;
console.log(primary);   // "red"
console.log(secondary); // "green"

// Skip an element with a comma
const [, , third] = colors;
console.log(third);     // "blue"

The Three Dots: ...

JavaScript uses ... (three dots) for two different purposes depending on context. The syntax looks identical, but the behavior is opposite:

Spread Expands / Unpacks One collection → many items ...array → a, b, c Rest Collects / Gathers Many items → one collection a, b, ...rest ← items

Spread vs Rest: Key Distinction

Spread ... Rest ...
Direction Expands items out Gathers items in
Where used Function calls, array/object literals Function parameters, destructuring
Position Can appear anywhere Must be last
Result type Individual values Array or Object

How to Apply Destructuring

1
Identify the source. Is it an object or an array?
2
Choose brackets. Use { } for objects, [ ] for arrays.
3
List the variables. For objects, names must match keys. For arrays, pick any names.
4
Add extras. Rename with :, set defaults with =, collect leftovers with ...rest.
5
Assign. Place the destructuring pattern on the left side of =.

Example: Spread in Arrays

JS
const fruits = ["apple", "banana"];
const veggies = ["carrot", "pea"];

// Combine into a new array
const food = [...fruits, ...veggies];
// ["apple", "banana", "carrot", "pea"]

// Clone an array (shallow copy)
const copy = [...fruits];
// ["apple", "banana"]

Example: Rest in Destructuring

JS
const scores = [98, 85, 72, 91, 66];

// Grab the first, collect the rest
const [top, ...others] = scores;

console.log(top);    // 98
console.log(others); // [85, 72, 91, 66]
JS
const user = { id: 1, name: "Ada", age: 36, role: "dev" };

// Pull id, gather everything else
const { id, ...profile } = user;

console.log(profile); // { name: "Ada", age: 36, role: "dev" }

Example: Spread in Objects

JS
const defaults = { theme: "dark", lang: "en", debug: false };
const userPrefs = { theme: "light", fontSize: 16 };

// Merge: userPrefs overrides defaults
const settings = { ...defaults, ...userPrefs };

// { theme: "light", lang: "en", debug: false, fontSize: 16 }

Destructuring in Function Parameters

JS
// Without destructuring
function greet(user) {
  return `Hello, ${user.name}! Age: ${user.age}`;
}

// With destructuring (cleaner!)
function greet({ name, age }) {
  return `Hello, ${name}! Age: ${age}`;
}

// Rest parameters
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10

Common Mistakes

✕ Wrong Brackets
Using [ ] to destructure an object or { } for an array. Objects need { }, arrays need [ ].
✕ Rest Not Last
Placing ...rest before other variables. Rest must always be the last element in the pattern.
✕ Mutating Originals
Assuming spread creates a deep copy. Spread only makes a shallow copy: nested objects are still shared.

Summary Table

Syntax What it Does Example
Object Destructure { a, b } = obj Extract by name { name } = user
Array Destructure [ a, b ] = arr Extract by position [ x, y ] = [1, 2]
Spread ...x in expression Expand items out [...a, ...b]
Rest ...x in pattern Collect remainder [a, ...rest]

Question 1 of 5

What does the following code output?
const { b, a } = { a: 1, b: 2 };
console.log(a, b);

Question 2 of 5

Given const [x, , z] = [10, 20, 30];
What are the values of x and z?

Question 3 of 5

Which statement correctly uses rest syntax in a function?

Question 4 of 5

What does { ...obj1, ...obj2 } do when both objects have the same key?

Question 5 of 5

What is the value of hostname after this code?
const { host: hostname = "0.0.0.0" } = {};