Destructuring assignment
Unpacks array elements or object properties into distinct variables.
Syntax
const [a, b] = array;
const { x, y } = object;
const { p = default, q: renamed } = object;
Examples
const [first, second] = [10, 20];
console.log(first, second);
Output
10 20
const { name, age } = { name: "Ada", age: 36 };
console.log(name, age);
Output
Ada 36
const { color = "blue", size: s = "M" } = { color: "red" };
console.log(color, s);
Output
red M
Notes
- Supports default values, renaming, nested patterns, and rest
elements.
- Swap variables without a temp: `[a, b] = [b, a]`.
- When destructuring an assignment (not a declaration), wrap object
patterns in parentheses: `({ a } = obj)`.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 49 |
| firefox | 41 |
| safari | 8 |
| edge | 14 |
| node | 6.0 |