What is JavaScript Array Destructuring?
Array destructuring in JavaScript is an expression that let’s us take the values inside an array and place them into distinct variables. It was introduced in ES6 and is a cleaner and more readable way than accessing array items by index.
The "Old" Way vs. The Destructuring Way
The Old Way (Pre-ES6):
Before array destructuring, we had to grab the values inside our arrays by their index number.
const colors = ['red', 'green', 'blue'];
const firstColor = colors[0];
const secondColor = colors[1];
console.log(firstColor); // Output: redIn this example, we have an array with three values (red, green, blue) and then work with the values within by:
- Creating a variable named
firstColorand setting its value by getting the first value in the array by index -colors[0] - Creating a second variable named secondColor and setting its value by getting the second value in the array by index -
colors[1]
The Destructuring Way:
const colors = ['red', 'green', 'blue'];
const firstColor = colors[0];
const secondColor = colors[1];
console.log(firstColor); // Output: redIn this example, we have the same array as before (red, green, blue), but instead of creating two variables with values set by index, we’re using an array destructuring expression:
- We define a pattern
[first, second]on the left side of our assignment operator=and on the right side we put the name of our arraycolors - Our pattern declares two variables
firstandsecondfirsttakes on the array’s first value,redsecondtakes on the array’s second value,green
Core Concepts & Syntax
Break this down into sub-headers (H3) to target specific long-tail queries.
Building off of what we’ve explained above, we’re going to destructure an array using an example and then use it throughout most of the core concepts and syntax below.
We’ll create an array of four popular car makes (carMakes) and destructure it into four different variables (usConsumer, usLuxury, jpConsumer, jpLuxury).
const carMakes = ["Ford", "Lincoln", "Toyota", "Lexus"];
const [usConsumer, usLuxury, jpConsumer, jpLuxury] = carMakes;Basic Assignment
Order matters when we destructure an array in JavaScript. The variable on the left maps to the index on the right.
// Array's first value is 'Ford' and then continues right
const carMakes = ["Ford", "Lincoln", "Toyota", "Lexus"];
//Destructuring's first variable is 'usConsumer' and then continues right
const [usConsumer, usLuxury, jpConsumer, jpLuxury] = carMakes;In this example, we can see this in action due to our variable values from destructuring:
Reading the array from left-to-right
- The first variable
usConsumerequals the first value in the arrayFord - The second variable
usLuxuryequals the second value in the arrayLincoln - The third variable
jpConsumerequals the third value in the arrayToyota - The Fourth variable
jpLuxuryequals the fourth value in the arrayLexus
Skipping Items
Even though order matters when we destructure, sometimes we want to skip a value without having to create a variable for it. We can do this by using a comma to skip an index/array item.
const numbers = [10, 20, 30, 40];
// Skip the second item (20)
const [first, , third] = numbers;
console.log(third); // Output: 30Let’s take our carMakes array and skip past the luxury makes in the list, meaning we want to skip past the second and fourth array items.
const carMakes = ["Ford", "Lincoln", "Toyota", "Lexus"];
const [usConsumer, , jpConsumer] = carMakes;
/*
Values:
usConsumer = Ford
jpConsumer = Toyota
*/To accomplish this, our destructuring looks a little different (from left-to-right):
- Our first variable is still
usConsumerand we still include a comma,right after it.- Its value is equal to the first array item
Ford
- Its value is equal to the first array item
- Now we want to skip our second value, so we don’t write a variable name, we represent the skip by adding another comma
, - Our second variable is now
jpConsumer- Its value is equal to the third array item
Toyota
- Its value is equal to the third array item
- And finally, we need to skip the fourth and final array item - because it’s the last one, we can just stop destructuring altogether, we don’t need another comma
,
Setting Default Values
When we’re destructuring we may try to grab a value from our array that isn’t there, this will result in an undefined.
For example, our carMakes array is still 4 values, but we’ll try and destructure a fifth.
const carMakes = ["Ford", "Lincoln", "Toyota", "Lexus"];
const [usConsumer, usLuxury, jpConsumer, jpLuxury, krConsumer] = carMakes;
/*
Values:
usConsumer = Ford
usLuxury = Lincoln
jpConsumer = Toyota
jpLuxury = Lexus
krConsumer = undefined
*/As we destructure, we add a fifth variable called krConsumerbut because there are only four items in our array, there's no value for krConsumer and therefore its value becomes undefined.
This may not seem like a big deal, but outside examples like this, real-world codebases dynamically change arrays based values returned from APIs, user input, etc. With that in mind, we can set default values to avoid having variables with undefined values.
Take a look at the code below:
const carMakes = ["Ford", "Lincoln", "Toyota", "Lexus"];
const [usConsumer, usLuxury, jpConsumer, jpLuxury, krConsumer = "Hyundai"] = carMakes;
/*
Values:
usConsumer = Ford
usLuxury = Lincoln
jpConsumer = Toyota
jpLuxury = Lexus
krConsumer = Hyundai
*/Taking a look at our krConsumer variable, you can see that we’re giving it the value Hyundai - we haven’t changed our array at all, this is done within our destructuring.
Now what if our array does include a fifth value? What will happen to our default value? Take a look at the example below.
const carMakes = ["Ford", "Lincoln", "Toyota", "Lexus", "Kia"];
const [usConsumer, usLuxury, jpConsumer, jpLuxury, krConsumer = "Hyundai"] = carMakes;
/*
Values:
usConsumer = Ford
usLuxury = Lincoln
jpConsumer = Toyota
jpLuxury = Lexus
krConsumer = Kia
*/We’ve added a fifth array item with the value Kia, and it overwrites our fallback value Hyundai. Ultimately the krConsumer variable has the value Kia.
Swapping Variables
Swapping variables with JavaScript destructuring is a great way to swap variable values without the need for a temporary variable - it is also a popular interview question (or so I hear).
We’ll have to ditch our carMakes array for this one since the syntax doesn’t line-up. Instead we’ll just swap the values of a couple of variables, num1 and num2.
let num1 = 5;
let num2 = 10;
// Swaps the variable values via destructuring
[num1, num2] = [num2, num1];
/*
Values:
num1 = 10
num2 = 5
*/On the onset it looks like this isn’t array destructuring because there isn’t a pre-existing array, but the [num1, num2] is still destructuring, however, in this case it’s destructuring an array literal [num2, num1]instead of a pre-existing array.
Using Destructuring with Functions
We can also use destructuring with functions, which is a great way to return multiple values.
function getResolution(type) {
if (type == '720p') {
return [1280, 720];
}
else if (type == '1080p') {
return [1920, 1080];
}
}
const [width, height] = getResolution('720p');
/*
Values:
width: 1280
height: 720
*/In our example, our function getResolution returns the width and height for either 720p or 1080p depending on what the argument type is set to. We then destructure those returned values into width and height via [width, height].
The Rest Pattern (...)
The rest pattern written …, allows us to capture the remaining values in the array - or stated another way, the rest pattern allows us to capture “the rest” of the array.
Using our carMakes array we’ll destructure by grabbing the first value normally and then grab the rest using the rest pattern.
const carMakes = ["Ford", "Lincoln", "Toyota", "Lexus"];
const [firstValue, ...restValues ] = carMakes;
/*
Values:
firstValue = Ford
restValues = ["Lincoln", "Toyota", "Lexus"]
*/You can see from our example that we grab the first value of our carMakes array with firstValue in our destructuring. But then we grab the rest of the array (the remaining three values) by creating a new array called restValues using the rest pattern …
FAQ: Common Questions About Array Destructuring
1. Can I destructure nested arrays in JavaScript?
Yes, you can unpack nested arrays by matching the structure of the array on the left-hand side of the assignment. This is often called "deep destructuring." You simply use square brackets inside your declaration to match the nested array's position.
const numbers = [1, [2, 3], 4];
// We use nested brackets to match the 2 and 3
const [a, [b, c], d] = numbers;
console.log(b); // Output: 2
console.log(c); // Output: 32. What happens if I destructure an index that doesn't exist?
If you try to unpack a value that does not exist in the array, the variable will be set to undefined. It does not throw an error. This is why using default values (e.g., const [a = 1] = []) is a best practice when working with unpredictable data sources like APIs.
const fruits = ['apple'];
const [first, second] = fruits;
console.log(first); // Output: apple
console.log(second); // Output: undefined`3. Can I combine array and object destructuring?
Yes, you can mix array and object destructuring in a single expression. This is extremely useful when dealing with JSON data, where you might have an array of objects.
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
// Extract the name of the first user
const [{ name }] = users;
console.log(name); // Output: Alice4. Is array destructuring faster than standard indexing?
No, array destructuring is generally not faster than standard index access (e.g., arr[0]) in terms of raw execution speed. However, the performance difference is negligible in most applications. The primary benefit of destructuring is developer experience: it improves code readability, maintainability, and reduces lines of code.
5. Is array destructuring the same as object destructuring?
No, array destructuring and object destructuring are not the same, even though they use similar syntax.
Array destructuring extracts values from an array based on their position (index). The variable names can be anything, but the order matters.
// Array Destructuring
const [width, height] = [1920, 1080];Object destructuring extracts values from an object based on property names (keys). Here, the property names must match, and the order does not matter.
// Object Destructuring
const { width, height } = { width: 1920, height: 1080 };
