Destructuring Arrays and Objects in JavaScript

Learn on destructuring in JavaScript via examples - including array, objects and nested structures.
Published 2023-04-26 5 min read
Destructuring Arrays and Objects in JavaScript

Destructuring in JavaScript is a way to unpack values from arrays and properties from objects into separate variables during the assignment. It makes your code cleaner and more readable. Why should you care about destructuring? Because it simplifies your code and makes it easier to understand and shorter. We are going to focus on two main types of destructuring - array and object destructuring. At the end, we’ll discuss destructuring of the more complex, nested structures and using default values.

Array Destructuring

Array destructuring is a quick way to assign elements of an array to variables. Let’s dive right into it and look at some examples.

Assigning elements to variables

Consider the following array:

const colors = ["red", "green", "blue"];

With array destructuring, you can assign the elements to variables like this:

const [color1, color2, color3] = colors;
console.log(color1); // 'red'
console.log(color2); // 'green'
console.log(color3); // 'blue'

Skipping elements when destructuring

You don’t have to assign every element in the array. You can skip elements using commas:

const [, , color3] = colors;
console.log(color3); // 'blue'

Although I have to say I’m not a fan of this particular syntax, as you can see it doesn’t look great. It can be pretty messy especially if there are many elements in the array.

Using destructuring assignment in practice

Swapping variables without a temporary variable

You can use destructuring to swap values between two variables without needing a third, temporary variable:

let a = 1;
let b = 2;

[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1

Returning multiple values from a function

Functions can return arrays, which you can then destructure to get multiple values:

function getFullName() {
  return ["John", "Doe"];
}

const [firstName, lastName] = getFullName();
console.log(firstName); // 'John'
console.log(lastName); // 'Doe'

 

Object Destructuring

Object destructuring allows you to extract properties from objects and assign them to variables. Again we’ll go directly to examples.

Assigning properties to variables

Here’s a simple object with some properties:

const person = {
  name: "Alice",
  age: 30,
};

You can destructure the object and assign its properties to variables like this:

const { name, age } = person;
console.log(name); // 'Alice'
console.log(age); // 30

Of course, you can extract and assign only selected properties from objects.

Renaming variables during destructuring

Sometimes, you might want to give the variables different names than the object properties. You can do this with the following syntax:

const { name: personName, age: personAge } = person;
console.log(personName); // 'Alice'
console.log(personAge); // 30

Simplifying function parameter handling 

Destructuring can make handling function parameters more straightforward, especially when dealing with optional parameters or objects:

function greet({ name, age }) {
  console.log(`Hello, ${name}! You are ${age} years old.`);
}

greet(person); // 'Hello, Alice! You are 30 years old.'

 

Nested Destructuring

You can use object destructuring to access values in nested structures. You can even combine array and object destructuring for even more complicated data.

Accessing deeply nested properties

Suppose you have a complex data structure like this:

const data = {
  user: {
    name: "Bob",
    age: 25,
    address: {
      city: "New York",
      country: "USA",
    },
  },
};

You can use nested destructuring to access the inner properties:

const {
  user: {
    name,
    age,
    address: { city, country },
  },
} = data;

console.log(name); // 'Bob'
console.log(age); // 25
console.log(city); // 'New York'
console.log(country); // 'USA'

 

Simplifying complex data structures

Nested destructuring can help you simplify complex data structures when passing them to functions or when working with API responses.

For example, consider the following API response:

const apiResponse = {
  status: "success",
  data: {
    user: {
      id: 1,
      name: "Alice",
      posts: [
        { id: 101, title: "Hello, world!" },
        { id: 102, title: "My second post" },
      ],
    },
  },
};

You can extract the user’s name and their first post’s title using nested destructuring:

const {
  data: {
    user: {
      name,
      posts: [{ title: firstPostTitle }],
    },
  },
} = apiResponse;

console.log(name); // 'Alice'
console.log(firstPostTitle); // 'Hello, world!'

Now let’s say you would like to get a second post title. To do that just leverage what you’ve learned about array destructuring assignment.

const {
  data: {
    user: {
      posts: [, { title: secondPostTitle }],
    },
  },
} = apiResponse;

console.log(secondPostTitle); // 'My second post'

 

Default Values and Destructuring

You can provide default values for variables during destructuring, which is helpful when dealing with undefined or missing properties.

 

Handling undefined or missing properties

const person = {
  name: "Charlie",
};

const { name, age = 30 } = person;

console.log(name); // 'Charlie'
console.log(age); // 30

 

Simplifying optional parameters in functions

Default values in destructuring can make it easier to work with optional parameters in functions:

function printNameAndAge({ name, age = "unknown" }) {
  console.log(`${name} is ${age} years old.`);
}

printNameAndAge({ name: "David" }); // 'David is unknown years old.'

 

Just to recap - In this article, we explored the power and simplicity of JavaScript destructuring, covering array and object destructuring, nested destructuring, and default values. Destructuring can make your code cleaner, more readable, and easier to understand. This feature is widely used in many JavaScript libraries, so you’ll for sure encounter it. Now you can use it on your own, to create more idiomatic JavaScript code. Just one more thing - remember that even the best idea can be overdone. So before rewriting all your code to destructuring assignment, take a second to consider your options and choose the best one.

#javascript