Destructuring, Spread (...) & Rest Parameters
Quick Overview
The same `...` gathers on the left and expands on the right: `[a, ...rest]` collects the remainder, `[...a, ...b]` combines two arrays. Both produce new values, so the originals are never mutated.
Deep Dive
1. Modern Syntax Shortcuts
ES6 introduced Destructuring for unpacking values from arrays or objects directly into distinct variables, and the versatile Spread/Rest operator (...).
2. Why It Matters
Destructuring eliminates verbose const name = user.name repetition, while Spread allows clean, non-mutating shallow copying and object merging.
3. Object & Array Destructuring
// Object Destructuring
const user = { id: 101, name: "Maria", role: "Admin" };
const { name, role } = user;
console.log(name, role); // "Maria" "Admin"
// Array Destructuring & Rest Operator
const colors = ["Red", "Green", "Blue", "Yellow"];
const [primary, secondary, ...otherColors] = colors;
console.log(primary); // "Red"
console.log(otherColors); // ["Blue", "Yellow"]
4. The Spread Operator (...)
Use spread ... to copy or merge objects and arrays without mutating the original source:
const defaultSettings = { theme: "dark", notifications: true };
const userSettings = { theme: "light" };
// Merge objects (User settings override defaults)
const finalConfig = { ...defaultSettings, ...userSettings };
console.log(finalConfig); // { theme: "light", notifications: true }
5. Common Mistakes
- Destructuring Undefined or Null: Destructuring properties from
undefinedornull(e.g.const { name } = undefined) throws an uncaughtTypeError. Always supply default fallback objects! - Confusing Spread with Deep Copying: Spread (
{ ...obj }) creates a shallow copy. If the object contains nested objects, nested properties still share references in memory!
6. Try It Yourself
Write it yourself. The tests below run against your code.
Extract User Details with Object Destructuring
Examples
7. Next Steps
Use destructuring for clean function arguments. Next, let's understand the difference between Shallow Copy and Deep Copy!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.