Basic Array Destructuring Syntax
You'll learn how to use square brackets to extract array elements directly into individual variables in a single, elegant line.
What is the Basic Syntax?
Array destructuring uses square brackets on the left side of an assignment to unpack values from an array into separate variables. Instead of accessing elements by index repeatedly, you can extract multiple values at once.
The basic pattern looks like this:
const [firstVar, secondVar, thirdVar] = arrayName;
Each variable in the square brackets corresponds to an element at the same position in the array.
How It Works
Think of destructuring like unpacking a suitcase. Instead of pulling out items one at a time (const shirt = suitcase[0], const pants = suitcase[1]), you lay everything out at once and assign each item to its spot.
const colors = ['red', 'green', 'blue'];
// Without destructuring
const first = colors[0];
const second = colors[1];
const third = colors[2];
// With destructuring
const [first, second, third] = colors;
console.log(first); // 'red'
console.log(second); // 'green'
console.log(third); // 'blue'
The variables first, second, and third now hold the values from positions 0, 1, and 2 respectively.
Why This Matters
This syntax dramatically improves code readability when working with arrays where position has meaning. Instead of index numbers scattered throughout your code, you have descriptive variable names that make your intent clear. It's particularly useful when a function returns an array of related values.
Key Takeaway: Array destructuring uses square brackets [ ] on the left side of an assignment to extract array elements into individual variables based on their position, making your code cleaner and more expressive.