Destructuring assignment
Unpacks values from an array or object into separate variables.
Available since: ES2015
Syntax
const [a, b] = array / const { a, b } = objectExamples
From an object:
const user = { name: 'Anna', age: 25 };
const { name, age } = user;
console.log(name, age);Output:
Anna 25From an array, with skipping and swapping:
const [first, , third] = ['a', 'b', 'c'];
console.log(first, third);
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x, y);Output:
a c
2 1Renaming, defaults and function parameters:
const { name: userName, role = 'guest' } = { name: 'Oleg' };
console.log(userName, role);
const greet = ({ name, city = 'unknown' }) => `${name} from ${city}`;
console.log(greet({ name: 'Anna' }));Output:
Oleg guest
Anna from unknownNotes
A default is used only for undefined, not for null. Destructuring undefined or null throws a TypeError.
See also
- Spread syntax — Three dots spread an array or object into separate items.
- Rest parameters — Collects the remaining function arguments into an array.
- Default parameters — A parameter's value when no argument is passed.
- Object.entries — Returns an array of property name and value pairs.
Related recipes
In the tutorial
- Destructuring — Array and object destructuring in JavaScript — unpacking values into variables in one line.