Array destructuring is a syntax in JavaScript that allows you to unpack values from arrays into distinct variables in a concise and readable way.

💡 What is Array Destructuring?
It extracts elements from an array and assigns them to variables using a syntax that mirrors the array structure.
Basic Syntax
Use square brackets on the left-hand side to declare variables that correspond to positions in the array:
📌 Deep Dive: Simple Extraction
const colors = ['red', 'green', 'blue'];
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
console.log(third); // "blue"
"green"
"blue"
Skipping Items
You can skip elements by leaving gaps with commas:
📌 Deep Dive: Skipping Elements
const numbers = [10, 20, 30, 40];
const [, , third] = numbers;
console.log(third); // 30
Default Values
If the array doesn't have a value at a position, you can assign a default:
📌 Deep Dive: Default Values
const names = ['Alice'];
const [first = 'John', second = 'Doe'] = names;
console.log(first); // "Alice"
console.log(second); // "Doe"
"Doe"
Rest Pattern
Collect remaining elements into an array using the rest syntax ...:
📌 Deep Dive: Rest Pattern
const fruits = ['apple', 'banana', 'cherry', 'date'];
const [first, ...others] = fruits;
console.log(first); // "apple"
console.log(others); // ["banana", "cherry", "date"]
["banana", "cherry", "date"]
💡 Why Use Array Destructuring?
- Improves code readability by clearly showing intended variable assignments.
- Reduces the need for multiple lines of code accessing array elements.
- Supports default values and skipping elements easily.
| Traditional | Array Destructuring |
|---|---|
const a = arr[0]; | const [a] = arr; |
const b = arr[1]; | const [, b] = arr; |
| Multiple lines | Single line |
⚠️ Common Pitfall
Do not confuse array destructuring with object destructuring. They use different syntax (square brackets for arrays, curly braces for objects).
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What will const [a, , c] = [1, 2, 3]; assign to c?
Question 2 of 2
Which syntax correctly collects remaining elements after the first?
Loading results...