logo
logo

Destructuring Cheatsheet

What is destructuring?

Destructuring is a feature introduced in ES6 that makes it easier to work with arrays and objects by allowing you to extract data from them and assign it to variables. You can use destructuring on the left-hand side of an assignment expression to unpack values from arrays or properties from objects into separate variables.

Destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

Destructuring arrays

Destructuring arrays is a simple way to extract values from arrays and assign them to variables. To destructure an array, you need to use square brackets (
[]
) and the names of the variables you want to assign the values to. Here's an example:
const [a, b] = [1, 2];
console.log(a); // output: 1
console.log(b); // output: 2
In this example, we are destructuring an array of numbers and assigning the first value to
a
and the second value to
b
.

You can also use destructuring to assign default values to variables. Here's an example:

const [a = 1, b = 2] = [3];
console.log(a); // output: 3
console.log(b); // output: 2
In this example, we are destructuring an array with only one value
[3]
and assigning the first value to
a
and the second value to
b
. Since there is no second value in the array,
b
is assigned the default value of
2
.

Skipping values while destructuring

You can skip values while destructuring an array or an object. To skip a value, you just leave a comma (,) in the destructuring syntax where the value should be assigned. Here's an example:

const [a, , c] = [1, 2, 3];
console.log(a); // output: 1
console.log(c); // output: 3

In this example, we are destructuring an array of three values [1, 2, 3] and assigning the first value to a and the third value to c. We skipped the second value by leaving a comma in the destructuring syntax.

Using the rest pattern with destructuring

You can also use the rest pattern with destructuring to assign the remaining values of an array to a new variable. The rest pattern is denoted by three dots (...). Here's an example:

const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // output: 1
console.log(b); // output: 2
console.log(rest); // output: [3, 4, 5]

In this example, we are destructuring an array of five values [1, 2, 3, 4, 5] and assigning the first value to a, the second value to b, and the remaining values to a new variable rest using the rest pattern.

Object Destructuring

Object destructuring allows us to extract individual properties from an object and assign them to variables or constants. It can help make our code more concise, readable, and maintainable.

Syntax for Object Destructuring

To use object destructuring, we use curly braces {} to indicate the properties we want to extract from the object, and then assign them to variables or constants.

const myObject = {
  firstName: "Chris",
  lastName: "Jones",
  age: 30,
  email: "[email protected]"
};

const { firstName, lastName } = myObject;

console.log(firstName); // "Chris"
console.log(lastName); // "Jones"
In this example, we are destructuring the
firstName
and
lastName
properties of
myObject
and assigning them to variables with the same name. We can then use those variables in our code.

Assigning Object Properties to Variables Using Different Names

We can also assign object properties to variables using different names than the original property name. This can be useful when we want to give the variables more meaningful names, or avoid naming conflicts with existing variables.

const { firstName: first, lastName: last } = myObject;

console.log(first); // "Chris"
console.log(last); // "Jones"
In this example, we are destructuring the
firstName
and
lastName
properties of
myObject
, but assigning them to variables with different names:
first
and
last
.

Providing Default Values for Object Properties

If an object property is undefined, we can provide a default value using the equals sign (=).

const { firstName = "Unknown", lastName = "Unknown" } = myObject;

console.log(firstName); // "Chris"
console.log(lastName); // "Jones"
In this example, we are destructuring the
firstName
and
lastName
properties of
myObject
. If either property is undefined, the default value of "Unknown" is used.

Destructuring Object Parameters in Functions

We can also destructure object parameters in functions. This can be a useful technique to make our code more concise and readable.

function validateUser({ user, isValid }) {
  console.log(user);
  console.log(isValid);
}

validateUser({ user: "Bob", isValid: true }); // "Bob", true
In this example, we are destructuring the
user
and
isValid
properties of the object passed to the
validateUser
function. This makes it easy to access those properties without having to write out the full object syntax.

Nested Data Structures

Nested data structures refer to objects and arrays that are nested inside other objects or arrays. In other words, these data structures are contained within other data structures. For example, an object that contains an array, which in turn contains an object, is a nested data structure.

Let's take a look at an example of a nested data structure:

const myObject = {
  title: "My address book",
  entries: [
    {
      name: "Bob",
      number: "555-555",
      address: "123 Fake Street"
    }
  ],
  myPhone: "5111"
}
In this example,
myObject
is an object that contains an array called
entries
. The
entries
array contains an object with three keys:
name
,
number
, and
address
.

Destructuring Nested Objects and Arrays

Destructuring allows us to extract values from objects and arrays and assign them to variables. We can also use destructuring to extract values from nested objects and arrays.

Let's take a look at an example of destructuring a nested object:

const { title, entries } = myObject;
console.log(title); // "My address book"
console.log(entries); // [{ name: "Bob", number: "555-555", address: "123 Fake Street" }]
In this example, we use destructuring to extract the
title
and
entries
values from
myObject
. The
entries
value is an array that contains an object, which we can further destructure.

Let's take a look at an example of destructuring a nested array:

const [{ name, number, address }] = entries;
console.log(name); // "Bob"
console.log(number); // "555-555"
console.log(address); // "123 Fake Street"
In this example, we use destructuring to extract the
name
,
number
, and
address
values from the first object in the
entries
array.

We can also alias destructured variables to avoid naming conflicts:

const myAddressObject = {
  name: "Billy Bobby",
  address: "456 Fake Street"
}
const { name: myName, address: myAddress } = myAddressObject;
console.log(myName); // "Billy Bobby"
console.log(myAddress); // "456 Fake Street"
In this example, we use aliasing to rename
name
and
address
to
myName
and
myAddress
, respectively.

Looping Through Nested Data Structures and Destructuring Them

We can also loop through nested data structures and use destructuring to extract values. Let's take a look at an example, looping through the following array of entries:

const entries = [
  { name: 'John', address: '123 Main St', other: { email: '[email protected]' } },
  { name: 'Jane', address: '456 Elm St', other: { email: '[email protected]' } },
  { name: 'Bob', address: '789 Oak St', other: { email: '[email protected]' } }
];
for (const { name, address } of entries) {
  console.log(`${name}: ${address}`);
}
In this example, we use a
for of
loop to iterate over each object in the
entries
array. We then destructure the
name
and
address
values from each object and use them in a
console.log()
statement.

We can also destructure values from nested objects within the loop:

for (const { name, address, other: { email } } of entries) {
  console.log(`${name}: ${address} (${email})`);
}
In this example, we use destructuring to extract the
email
value from the nested
other
object.