JSJavaScript · Lesson 10 of 14

Destructuring, Spread & Rest

ES6 destructuring lets you unpack arrays and objects in a single expression. Combined with spread and rest, it makes JavaScript feel dramatically less verbose. Fair warning: it also makes clever one-liners dramatically easier to write.

JavaScript
// Array destructuring
const [a, b, c] = [1, 2, 3]
console.log(a, b, c)  // 1 2 3

// Skip elements with commas
const [first, , third] = [1, 2, 3]
console.log(first, third)  // 1 3

// Default values
const [x = 10, y = 20] = [5]
console.log(x, y)  // 5 20

// Swap without temp variable
let p = 1, q = 2;
[p, q] = [q, p]
console.log(p, q)  // 2 1

// Rest elements
const [head, ...tail] = [1, 2, 3, 4, 5]
console.log(head)  // 1
console.log(tail)  // [2, 3, 4, 5]

// Object destructuring
const user = { name: "Alice", age: 30, city: "Paris" }
const { name, age } = user
console.log(name, age)  // Alice 30

// Rename while destructuring
const { name: userName, city: location = "Unknown" } = user
console.log(userName, location)  // Alice Paris

// Nested destructuring
const config = {
  server: { host: "localhost", port: 8080 },
  db: { name: "myapp", user: "admin" }
}
const { server: { host, port }, db: { name: dbName } } = config
console.log(host, port, dbName)  // localhost 8080 myapp
JavaScript
// Spread operator (...)
const arr1 = [1, 2, 3]
const arr2 = [4, 5, 6]
const combined = [...arr1, ...arr2]         // [1, 2, 3, 4, 5, 6]
const copy     = [...arr1]                  // shallow copy
const inserted = [0, ...arr1, 4]           // [0, 1, 2, 3, 4]

// Spread with objects
const base = { color: "blue", size: 10 }
const updated = { ...base, size: 20, weight: 5 }  // override size
console.log(updated)  // { color: 'blue', size: 20, weight: 5 }

// Merge objects (last wins on conflict)
const merged = { ...base, ...{ color: "red", opacity: 0.5 } }

// Rest parameters in functions
function sum(...nums) {
  return nums.reduce((acc, n) => acc + n, 0)
}
console.log(sum(1, 2, 3, 4, 5))  // 15

// Destructuring in function parameters
function displayUser({ name, age, role = "user" }) {
  console.log(`${name} (${age}) — ${role}`)
}
displayUser({ name: "Bob", age: 25 })         // Bob (25) — user
displayUser({ name: "Alice", age: 30, role: "admin" })  // Alice (30) — admin

// Destructuring in loops
const users = [
  { id: 1, name: "Alice", score: 95 },
  { id: 2, name: "Bob",   score: 87 },
]
for (const { name, score } of users) {
  console.log(`${name}: ${score}`)
}
◆ Note
Spread creates shallow copies — nested objects are still references. { ...obj } and [...arr] are fine for one-level-deep copies. For deep cloning, use structuredClone(obj) (modern JS) or JSON.parse(JSON.stringify(obj)) (lossy but widely supported).