DEV Community

Cover image for Destructuring in JavaScript
Honeybadger Staff for Honeybadger

Posted on • Originally published at honeybadger.io

Destructuring in JavaScript

This article was originally written by Adebayo Adams on the Honeybadger Developer Blog.

When building software with JavaScript, arrays and objects are the first options that come to mind when declaring related or groups of values in your code because they are arguably the most flexible data types in JavaScript. However, although the objects or arrays often contain related values, you rarely need the whole object or array at once; you only use a part of the object or arrays at a time. Digging deep into the array or object to get the necessary value or properties can be very frustrating.

In this article, you will learn about destructuring in JavaScript, the benefits of destructuring, how to destructure arrays and objects, and how to use it for easier data access in your applications. You will also learn about mixed destructuring, the spread operator in JavaScript, and how to destructure parameters.

Note: Destructure is an English word that means to destroy the structure of something.

Next, let's look at what you need to get the most out of this article.

Prerequisites

To follow this tutorial, you only need to have a basic understanding of JavaScript. Knowledge of variables, arrays, objects, functions, and parameters would be beneficial.

Now that you know what you need to follow along, I’ll briefly introduce the concepts of arrays and objects in JavaScript in the next section.

Arrays and objects

As mentioned above, destructuring mainly works for objects and arrays, so I'll briefly describe those in this section.

Arrays

An array in JavaScript is a collection of elements a numerical index can access. The elements in an array can be of any data type, including numbers, strings, and even other arrays or objects.

Arrays are created using square brackets, and individual elements can be accessed using their index, which starts at 0. Below is an example of how to create an array in JavaScript:

let arr = [1, "two", 3, "four"];
console.log(arr[1]); // returns "two"
Enter fullscreen mode Exit fullscreen mode

The code above creates an array called arr that contains four elements (i.e., the numbers 1 and 3 and the strings two and four) and then logs the second value in the array, which is the index 1 to the console. You can read more about JavaScript arrays here

Next, let's look at objects in the next section.

Objects

Objects in JavaScript are collections of key-value pairs. The keys in an object are strings, while the values can be of any data type. Objects are created using curly braces, and individual properties can be accessed using dot notation or square brackets. Here is an example of creating an object in JavaScript:

let obj = {
  name: "John Doe",
  age: 30,
  hobbies: ["reading", "traveling"]
};
console.log(obj.name); // returns "John Doe"
Enter fullscreen mode Exit fullscreen mode

The code above creates an object called obj that has three properties: name, age, and hobbies. The value of the name property is a string, "John Doe", the value of the age property is a number, 30, and the value of the hobbies property is an array.

The code then logs the name property using the dot notation, which returns "John Doe". You can read more about JavaScript objects here

Now that you know what arrays and objects are in JavaScript, let's look at what destructuring is in JavaScript.

Destructuring

Destructuring in JavaScript is dissecting data structures, arrays, and objects, in this case, to easily access the values inside them. Destructuring helps to unpack values from arrays and objects into distinct variables, so you do not have to dig through large arrays or objects to get the values you need.

JavaScript allows you to destructure arrays, objects, and function parameters. In the next section, let's look at how to destructure arrays in JavaScript.

Array destructuring

In this section, I will show you how to use array destructuring in JavaScript.

The basic syntax for array destructuring uses square brackets on the left-hand side of an assignment statement and the array on the right-hand side. For example, to extract the first element of an array and assign it to a variable, you can use the following code:

let numbers = [1, 2, 3, 4, 5];
let [firstNumber] = numbers;
console.log(firstNumber); // returns 1
Enter fullscreen mode Exit fullscreen mode

The code above creates an array called numbers that contains five numbers and then extracts the first number in the array and assigns it to a variable called firstNumber. Finally, the code logs firstNumber in the console, which should return 1.

Multiple elements

You can also extract multiple elements from an array and assign them to multiple variables:

let numbers = [1, 2, 3, 4, 5];
let [firstNumber, secondNumber, thirdNumber] = numbers;
console.log(firstNumber, secondNumber, thirdNumber); // returns 1 2 3
Enter fullscreen mode Exit fullscreen mode

The code above extracts the first three elements of the array and assigns them to the variables firstNumber, secondNumber, and thirdNumber, respectively, and logs them to the console:

multiple elements

Nested arrays

You can also use destructuring to extract elements from nested arrays:

let nestedArrs = [[1,2], [3,4], [5,6]];
let [firstArr, secondArr, thirdArr] = nestedArrs;
console.log(firstArr, secondArr, thirdArr);
Enter fullscreen mode Exit fullscreen mode

The example above creates a nestedArrs array, extracts the first three elements of the nested array, and logs them to the console:

nested arrays

Let's look at how to destructure objects in the next section.

Object destructuring

JavaScript allows you to extract properties from an object and assign them to variables. This feature is handy when working with large objects or extracting specific properties from an object. In this section, I'll show you how to use object destructuring in JavaScript.

The basic syntax for object destructuring uses curly braces on the left-hand side of an assignment statement and the object on the right-hand side. For example, to extract a property called "brand" from an object and assign it to a variable, you can use the following code:

let car = { brand: "Honda", color: "red"};
let { brand } = car;
console.log(brand); // returns "Honda"
Enter fullscreen mode Exit fullscreen mode

The code above creates an object called car that has two properties (i.e., brand and color), uses object destructuring to extract the brand property of the object and assign it to a variable called "brand", and then logs the value to the console:

object destructuring

Multiple properties

You can also extract multiple properties from an object and assign them to multiple variables:

const car = {
    brand: 'Ford',
    year: 2015,
    color: 'blue',
}
let { brand, year } = car;
console.log( brand, year ); // returns "Ford" and "2015"
Enter fullscreen mode Exit fullscreen mode

The code above extracts the brand and year properties of the object and assigns them to the variables brand and year, respectively.

Nested objects

You can also use destructuring to extract properties from nested objects:

let address = { street: "12 Benson Street", city: "Maryland", state: "Lagos" };
let person = { name: "Adams Ade", age: 25, address };
let { name, age, address: { city } } = person;
console.log(name, age, city);
Enter fullscreen mode Exit fullscreen mode

The code above creates an address object and a person object with the address nested inside it and then extracts the name, and age properties from the person object and city property from the address object and assigns them to the variables name, age, and city, respectively. It then logs them to the console:

nested objects result

Note: You can go as deep as you want; it doesn't matter how deep the object is.

Default values

Sometimes, you might need the value of an object property that might not be present in the given object. In that case, you can destructure the object and add default values for properties that might not be present in the object:

const job = {
  role: "Software Engineer",
  salary: 200000,
  applicationLink: "meta.com/careers/SWE-role/apply"
};
let { role, salary, isRemote = false } = job;
console.log(isRemote);
Enter fullscreen mode Exit fullscreen mode

The code above creates a job object that has no isRemote property and adds a default value for the isRemote property in case it is not present in the job object. In this instance, the variable isRemote is assigned the value false:

default values result

In addition to default values, you can also change the name of a property using an alias:

const job = {
  role: "Software Engineer",
  salary: 200000,
  applicationLink: "meta.com/careers/SWE-role/apply"
};
let { role: jobTitle, salary, isRemote = false } = job;
console.log(jobTitle);
Enter fullscreen mode Exit fullscreen mode

The code above will return the value of the role property correctly in the console:

aliases

Note: The jobTitle in this case is called an alias, and it is added after a : in front of the actual property name. Furthermore, you will get an error if you try to console.log(role) after declaring an alias.

Let's look at rest items in the next section.

Rest items

The rest operator (...) in JavaScript is a powerful feature that allows developers to gather the remaining items in an array or an object into a new array or object. This can be useful in various situations, such as when working with function arguments or destructuring arrays and objects.

For example, if you need the first three elements from an array of books and need the remaining elements that are in the array, you can use the rest operator:

const top20Books = [
    "1. To Kill a Mockingbird",
    "2. The Great Gatsby",
    "3. The Catcher in the Rye",
    "4. The Lord of the Rings",
    "5. The Hobbit",
    "6. The Diary of a Young Girl",
    "7. The Grapes of Wrath",
    "8. Animal Farm",
    "9. 1984",
    "10. The Adventures of Huckleberry Finn",
    "11. The Adventures of Tom Sawyer",
    "12. The Iliad",
    "13. The Odyssey",
    "14. The Republic",
    "15. The Inferno",
    "16. The Divine Comedy",
    "17. The Canterbury Tales",
    "18. Pride and Prejudice",
    "19. Jane Eyre",
    "20. Wuthering Heights"
  ];

  let [firstBook, secondBook, thirdBook, ...remainingBooks] = top20Books

  console.log(`Top three books on the list are ${firstBook}, ${secondBook}, and ${thirdBook}`)
Enter fullscreen mode Exit fullscreen mode

The code above creates a top20Books array containing 20 books, destructured the first three books and the remaining books, and then logs the first three books to the console:

top 3 books

The ...remainingBooks is an array that can be used like a regular array:

  console.log(...remainingBooks)
Enter fullscreen mode Exit fullscreen mode

The code above will log the remaining books in the array to the console:

remaining books array

Now that you know how rest items work in JavaScript, let's look at mixed destructuring in the next section.

Mixed destructuring

Mixed destructuring is a combination of both object destructuring and array destructuring; it allows you to extract values from arrays and objects in a single destructuring assignment.

For example, if you have an object with an array inside of it, you can destructure the object as well as the array with a single line:

const user = {
  name: "William Benson",
  age: 20,
  address: {
    city: "Maryland",
    state: "Lagos"
  },
  hobbies: ["Swimming", "Golf", "Writing"]
};

const { name, age, address: { city, state }, hobbies: [firstHobby] } = user;
Enter fullscreen mode Exit fullscreen mode

The code above creates a user object that has an address object and a hobbies object inside it and extracts name, age, city, state, and one of the hobbies using mixed destructuring. You can now use the values that you extracted:

console.log(`This user's name is ${name} and he is ${age} years old. He lives at ${city}, in ${state} state and one of his hobbies is ${firstHobby}`)
Enter fullscreen mode Exit fullscreen mode

The code above will log something like this to the console:

mixed destructuring result

Now that you know how to use mixed destructuring, let's look at how to destructure function parameters in the next section.

Destructuring function parameters

JavaScript allows you to extract values from an object or array passed as a parameter to a function. Destructuring parameters is quite straightforward, as you only need to use the destructuring syntax inside the function:

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

greet({ name: "Peter", age: 50 }); // returns Hello, Peter. You are 50 years old.
Enter fullscreen mode Exit fullscreen mode

You can also do the same for arrays:

const top10Books = [
    "1. To Kill a Mockingbird",
    "2. The Great Gatsby",
    "3. The Catcher in the Rye",
    "4. The Lord of the Rings",
    "5. The Hobbit",
    "6. The Diary of a Young Girl",
    "7. The Grapes of Wrath",
    "8. Animal Farm",
    "9. 1984",
    "10. The Adventures of Huckleberry Finn"
  ];

  function rateBooks([firstBook, secondBook, thirdBook, ...remainingBooks]) {
    console.log(`Top three books on the list are ${firstBook}, ${secondBook}, and ${thirdBook}`)
    console.log(`The runner-ups are: ${[...remainingBooks]}`)
  }
  rateBooks(top10Books)
Enter fullscreen mode Exit fullscreen mode

The code above creates an array of top10Books and a function that logs the first three books and the remaining books in the console. The result should look like this:

array parameters result

Benefits of destructuring

Now that you know how to use destructuring in JavaScript, let's look at why you should consider using destructuring.

Concise and readable code

One of the main benefits of destructuring is that it allows you to write more concise and readable code. By using destructuring, you can extract values from arrays and objects in a single line of code, making it easier to understand what the code is doing. This is particularly useful when working with large data structures, as it allows you to focus on the essential parts of the data rather than getting lost in the details.

Improved performance

Another benefit of destructuring is that it can improve the performance of your code. When you extract values from an array or object, you create a new variable that references the value. You can manipulate the value without affecting the original data structure. This can be particularly useful when working with large data sets, as it allows you to work with a smaller subset of the data, which can be more efficient.

Better handling of default values

Destructuring also allows you to set default values for variables. If the value you are trying to extract from an array or object is not present, the default value will be used instead. This is particularly useful when working with data that may be incomplete or missing specific values. By setting default values, you can ensure that your code will still work correctly even if the data is incomplete.

Easier handling of nested properties

Another benefit of destructuring is that it quickly extracts nested properties from an object. With destructuring, you can extract values with a single line of code, making it much easier to work with nested properties.

Better handling of function parameters

Finally, destructuring can also be used to extract values from function parameters. This allows you to easily extract specific values from an object or array passed as a parameter to a function. This can be particularly useful when working with complex data structures, as it allows you to focus on the specific values you need without navigating through the entire data structure.

Conclusion

Thanks for reading! Hopefully, this article achieved its aim of teaching you everything you need to know about destructuring in JavaScript. You’ve learned how to destructure arrays, objects, and function parameters, as well as how to destructure a mixed data structure.

Top comments (10)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

You can also destructure arrays as objects (strings too), which allows some interesting stuff:

let {length, [length-1]: last} = [9,8,7,6]
console.log(length, last)  // 4, 6

let {length, [length-1]: last} = "Hello world!"
console.log(length, last)  // 12 , '!'
Enter fullscreen mode Exit fullscreen mode

It's also worth mentioning that when destructuring arrays (or any iterable - it's the same syntax), you can also skip elements:

// skipping items in an array
let [,,third,,fifth] =  [8, 7, 6, 5, 4, 3]
console.log(third, fifth)  // 6, 4

// skipping items in another iterable type - string
let [,,third,,fifth] =  "abcdef"
console.log(third, fifth)  // 'c', 'e'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
equiman profile image
Camilo Martinez

I did not about this length trick. 🤯 thanks!

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You can have all kinds of fun with destructuring... if you're using my metho-number library, you can even do stuff like this - destructuring numbers!

let {[hex]:h, [oct]:o, [bin]:b} = 15 
console.log(h, o, b)  // 'f', '17',  '1111'
Enter fullscreen mode Exit fullscreen mode

Curious how this is working? Read more here and here.

Thread Thread
 
honeybadger_staff profile image
Honeybadger Staff

Neat!

Collapse
 
onlinemsr profile image
Raja MSR

The article provides a comprehensive guide on how to unpack values from objects and arrays using destructuring, along with examples and use cases. It also covers mixed destructuring, the spread operator, and destructuring parameters.

The post is a valuable resource for anyone looking to enhance their understanding of destructuring in JavaScript.

Thank you for sharing this insightful article! Keep up the good work! 👍

Collapse
 
efpage profile image
Eckehard

Using Proxies enables a nice pattern to get access to variable names during destructuring. See this posts:

Smart destructuring
The magic function

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Nice article!

Collapse
 
dumebii profile image
Dumebi Okolo

Thanks for sharing!

Collapse
 
ryansgi profile image
Ryan B

At risk of splitting hairs...

let [firstBook, secondBook, thirdBook, ...remainingBooks] = top20Books

This is an example of a SPREAD operator, not a REST operator. And while the operator is exactly the same in Javascript ... for both spread and rest, the usage is different.

Rest operators are typically used in method parameters to gather all the remaining arguments into a single array variable.

Put another way:

// REST operator usage
const listTopBooks = (fst, snd, trd, ...rem) => {
  console.log("First:", fst);
  console.log("Second:", snd);
  console.log("Third:", trd);
  console.log("Remaining:", rem);
}

// spread operator usage
listTopBooks(...top20Books.slice(0, 3));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
honeybadger_staff profile image
Honeybadger Staff

Noted, thanks!