JavaScript Array Destructuring: Complete Guide
Destructuring unpacks array values into variables in one line. Learn the syntax, default values, skipping elements, rest patterns, and practical use cases.
Array destructuring is a concise way to extract values from an array and assign them to variables in a single statement. It was introduced in ES6 and replaces the older pattern of accessing elements by index, one variable at a time.
const coordinates = [10, 20];
const x = coordinates[0];
const y = coordinates[1];Destructuring replaces those three lines with one, pulling both values out in a single statement instead of indexing into the array twice:
const [x, y] = [10, 20];
console.log(x); // 10
console.log(y); // 20The left side of the = mirrors the array structure. Each variable in the brackets receives the element at the corresponding position.
Basic Syntax
The pattern is const [var1, var2, ...] = array. You can use const, let, or var, and each variable name in the brackets maps to one element by position:
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
console.log(third); // "blue"If there are more variables than elements, the extras get undefined instead of throwing an error, since destructuring never fails on a length mismatch:
const [a, b, c] = [1];
console.log(a); // 1
console.log(b); // undefined
console.log(c); // undefinedSkipping Elements
Skip elements you do not need by leaving the position empty between commas, keeping the comma as a placeholder for the position:
const data = ["admin", "Alice", "alice@example.com", "active"];
const [, name, email] = data;
console.log(name); // "Alice"
console.log(email); // "alice@example.com"The first element "admin" is skipped. Only name and email are assigned. This is cleaner than writing const name = data[1]; const email = data[2], and it scales better as more positions need to be skipped.
Default Values
Provide fallback values for when the array is missing elements, so a variable never ends up as undefined just because the source array was shorter than expected:
const [a = 1, b = 2, c = 3] = [10];
console.log(a); // 10 (from array)
console.log(b); // 2 (default)
console.log(c); // 3 (default)Default values only apply when the element is undefined. An element that is null or another falsy value will still be assigned:
const [a = "default"] = [null];
console.log(a); // null (not "default", because null is not undefined)The Rest Pattern
Use ... to collect all remaining elements into a new array, after any variables that pick off individual elements from the front:
const scores = [85, 92, 78, 95, 88];
const [highest, second, ...rest] = scores;
console.log(highest); // 85
console.log(second); // 92
console.log(rest); // [78, 95, 88]rest is a new array containing everything after the first two elements. The rest pattern must be the last element in the destructuring pattern:
// Valid: rest at the end
const [first, ...rest] = [1, 2, 3];
// Invalid: rest not at the end
const [...rest, last] = [1, 2, 3]; // SyntaxErrorThis is the same ... syntax as the spread operator, but used on the left side of = instead of the right.
On the left, it collects. On the right, it spreads.
Swapping Variables
Destructuring makes variable swapping a one-liner without a temporary variable:
let a = "first";
let b = "second";
[a, b] = [b, a];
console.log(a); // "second"
console.log(b); // "first"This reads cleanly: put b in a's position and a in b's position. No temporary variable needed, since the array literal on the right is fully built before any assignment happens on the left.
Destructuring Function Returns
Functions that return arrays pair naturally with destructuring, letting the caller name each returned value instead of indexing into the result:
function getMinMax(numbers) {
return [Math.min(...numbers), Math.max(...numbers)];
}
const [min, max] = getMinMax([5, 2, 9, 1, 7]);
console.log(min); // 1
console.log(max); // 9This is a clean pattern for returning multiple values from a function without wrapping them in an object and naming each field. React's useState hook uses this exact pattern:
// React example (conceptual)
const [count, setCount] = useState(0);Destructuring Nested Arrays
Nest the brackets to match the array structure, so each level of nesting in the pattern lines up with a level of nesting in the data:
const matrix = [1, [2, 3], 4];
const [a, [b, c], d] = matrix;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4The inner [b, c] matches the inner array [2, 3]. You can nest as deeply as the data structure requires, though very deep nesting usually reads more clearly as separate statements.
Practical Use Cases
Parsing a split string. split() returns an array, so destructuring can name each piece immediately instead of storing the whole array first:
const [firstName, lastName] = "Alice Johnson".split(" ");
console.log(firstName); // "Alice"
console.log(lastName); // "Johnson"Extracting URL parts. Combining skipped positions with named variables pulls out only the segments you care about from a split URL path:
const url = "/users/42/posts/7";
const [, , userId, , postId] = url.split("/");
console.log(userId); // "42"
console.log(postId); // "7"Iterating with destructuring in a loop. When each array element is itself a small array, destructuring in the loop header names both parts on every iteration:
const entries = [
["name", "Alice"],
["role", "Developer"],
["city", "New York"]
];
for (const [key, value] of entries) {
console.log(`${key}: ${value}`);
}Common Mistakes
Forgetting that destructuring is position-based, not name-based. Choosing variable names that describe the data does not connect them to anything in the array itself:
// These variable names are arbitrary -- only position matters
const [apple, banana] = [1, 2];
console.log(apple); // 1 (first position)
console.log(banana); // 2 (second position)The variable names do not map to anything in the array. Only the order matters, so choosing clear, meaningful names is purely for the benefit of whoever reads the code later.
Accidentally using const reassignment with swapping:
// Error: const prevents reassignment
const [a, b] = [1, 2];
[a, b] = [b, a]; // TypeError: Assignment to constant variable
// Right: use let
let [x, y] = [1, 2];
[x, y] = [y, x];Use let when you plan to reassign destructured variables later, like in swaps.
Trying to use rest pattern in the middle:
// SyntaxError: rest element must be last
const [a, ...rest, b] = [1, 2, 3, 4];The rest pattern ... must always be the final element. After it collects the remaining elements, there is nothing left for variables after it.
Now that you can unpack arrays, learn how to clean up duplicates with removing duplicates from arrays, or move on to object destructuring for the same pattern with objects.
Rune AI
Key Insights
- Destructuring unpacks array values into variables using const [a, b] = arr syntax.
- You can skip elements with empty commas: const [, , third] = arr.
- Default values protect against undefined: const [a = 1] = [] gives a = 1.
- The rest pattern ... collects remaining elements: const [first, ...rest] = arr.
- Destructuring makes variable swapping a one-liner: [a, b] = [b, a].
Frequently Asked Questions
What happens if the array has fewer elements than variables?
Can I destructure nested arrays?
Does destructuring mutate the original array?
Conclusion
Array destructuring is one of the most satisfying features of modern JavaScript. It replaces multiple lines of index-based assignment with a single clean statement. Once you get comfortable with the syntax, you will use it everywhere -- for function returns, variable swaps, API responses, and pulling apart any array into named variables.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.