Array Destructuring
Learn to extract array values into variables with destructuring.
Destructuring is a convenient way to extract values from arrays and objects into distinct variables. It makes your code more readable and reduces the need for repetitive indexing. Array destructuring is especially useful when working with function returns, API responses, and coordinate pairs.
📚 Concepts & Theory
Basic Destructuring
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
// first = "red", second = "green", third = "blue"
Skipping Elements
const numbers = [1, 2, 3, 4, 5];
const [a, , c] = numbers;
// a = 1, c = 3 (skipped 2)
Default Values
const [x, y = 10] = [5];
// x = 5, y = 10 (default used)
Rest Pattern
const [head, ...tail] = [1, 2, 3, 4];
// head = 1, tail = [2, 3, 4]
Swapping Variables
let a = 1;
let b = 2;
[a, b] = [b, a];
// Now a = 2, b = 1
Nested Destructuring
const nested = [1, [2, 3]];
const [x, [y, z]] = nested;
// x = 1, y = 2, z = 3
With Functions
function getCoordinates() {
return [10, 20];
}
const [x, y] = getCoordinates();
🎯 Your Challenge
Given the array `[100, 200, 300, 400]`, use destructuring to extract the first value into `first`, skip the second, extract the third into `third`, and collect the rest into `remaining`.
📝 Starter Code
// Source array
const values = [100, 200, 300, 400];
// Destructure: first, skip, third, rest
const [first, , third, ...remaining] =
- Use empty slots (commas) to skip values
- ...rest must be last and collects remaining values
- Destructuring works with any iterable
- Default values use = syntax
Solution
const values = [100, 200, 300, 400];
const [first, , third, ...remaining] = values;
Explanation
We use destructuring with an empty slot (,,) to skip the second element. first gets 100, third gets 300, and ...remaining collects [400] (array with one element).
⚠️ Common Mistakes to Avoid
- Forgetting the comma to skip elements
- Using wrong bracket types
- Not understanding rest collects into an array
- Trying to destructure undefined values