JavaScript Destructuring

Destructuring assignment syntax

The destructuring assignment syntax unpacks object properties into variables:

let {firstName, lastName} = person;

It can also unpack arrays and any other iterable objects:

let [firstName, lastName] = person;

Object destructuring

Example

// Create an object
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50
};
// Destructuring
let {firstName, lastName} = person;

Try it yourself

The order of properties does not matter:

Example

// Create an object
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50
};
// Destructuring
let {lastName, firstName} = person;

Try it yourself

Note:

Destructuring is not destructive.

Destructuring does not change the original object.

Object default values

For missing properties, we can set default values:

Example

// Create an object
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50
};
// Destructuring
let {firstName, lastName, country = "US"} = person;

Try it yourself

Object property alias

Example

// Create an object
const person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 50
};
// Destructuring
let {lastName: name} = person;

Try it yourself

String destructuring

One use of destructuring is to unpack string characters.

Example

// Create a string
let name = "W3Schools";
// Destructuring
let [a1, a2, a3, a4, a5] = name;

Try it yourself

Note:

Destructuring can be used for any iterable object.

Array destructuring

We can extract array variables into their own variables:

Example

// Create an array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring
let [fruit1, fruit2] = fruits;

Try it yourself

Skipping array values

We can use two or more commas to skip array values:

Example

// Create an array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring
let [fruit1,,,fruit2] = fruits;

Try it yourself

Array position values

We can extract values from specific index positions in an array:

Example

// Create an array
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring
let {[0]: fruit1, [1]: fruit2} = fruits;

Try it yourself

Rest properties

You can use the rest properties at the end of destructuring syntax.

This syntax will store all remaining values into a new array:

Example

// Create an array
const numbers = [10, 20, 30, 40, 50, 60, 70];
// Destructuring
const [a, b, ...rest] = numbers;

Try it yourself

Destructure Map

Example

// Create a Map
const fruits = new Map([
  ["apples", 500],
  ["bananas", 300],
  ["oranges", 200]
]);
// Destructuring
let text = "";
for (const [key, value] of fruits) {
  text += key + " is " + value;
}

Try it yourself

Swap JavaScript variables

You can use destructuring assignment to swap the values of two variables:

Example

let firstName = "Bill";
let lastName = "Gates";
// Destructuring
[firstName, lastName] = [lastName, firstName];

Try it yourself