Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Destructuring assignment

Unpacks values from an array or object into separate variables.

Available since: ES2015

Syntax

const [a, b] = array / const { a, b } = object

Examples

From an object:

const user = { name: 'Anna', age: 25 };
const { name, age } = user;
 
console.log(name, age);

Output:

Anna 25

From 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 1

Renaming, 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 unknown

Notes

A default is used only for undefined, not for null. Destructuring undefined or null throws a TypeError.

See also

Related recipes

In the tutorial

  • Destructuring — Array and object destructuring in JavaScript — unpacking values into variables in one line.

Thanks for reading!

Donate to the site — we work hard for you.