How to Destructure Array in JavaScript: Simple Guide
In JavaScript, you can destructure an array using
const [a, b] = array; which assigns the first two elements of array to variables a and b. This syntax lets you extract values from arrays easily and assign them to variables in one line.Syntax
The basic syntax for array destructuring is const [var1, var2, ...] = array;. Here, var1, var2, etc., are variables that will hold the values from the array in order. You can skip elements by leaving empty spaces between commas.
javascript
const [first, second] = [10, 20]; console.log(first); // 10 console.log(second); // 20
Output
10
20
Example
This example shows how to destructure an array of colors into separate variables and print them.
javascript
const colors = ['red', 'green', 'blue']; const [primary, secondary, tertiary] = colors; console.log(primary); // red console.log(secondary); // green console.log(tertiary); // blue
Output
red
green
blue
Common Pitfalls
One common mistake is trying to destructure more variables than the array has elements, which results in undefined values. Another is forgetting that destructuring works by position, so order matters. Also, skipping elements requires leaving empty commas.
javascript
const arr = [1, 2]; const [a, b, c] = arr; console.log(c); // undefined // Correct way to skip second element: const [x, , z] = [10, 20, 30]; console.log(z); // 30
Output
undefined
30
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Basic destructuring | Assign variables from array elements by position | const [a, b] = [1, 2]; |
| Skip elements | Leave empty commas to skip values | const [a, , c] = [1, 2, 3]; |
| Default values | Assign default if element is undefined | const [a = 5] = []; |
| Rest operator | Collect remaining elements into array | const [a, ...rest] = [1, 2, 3]; |
Key Takeaways
Use
[var1, var2] = array to assign array elements to variables by position.Skip unwanted elements with empty commas like
[a, , c].Destructuring assigns
undefined if the array has fewer elements than variables.You can set default values to avoid
undefined when elements are missing.Use the rest operator
...rest to gather remaining elements into an array.