Topic 51 of 87
Destructuring
Overview
Destructuring assignment (ES6) is a special syntax that allows you to "unpack" values from arrays (or properties from objects) into distinct, standalone variables in a single, clean line of code.
It drastically reduces the amount of boilerplate code required to access nested data.
Syntax
Array Destructuring
javascript
const vehicles = ['Mustang', 'F-150', 'Expedition'];
// The Old Way
const car1 = vehicles[0];
const truck1 = vehicles[1];
// The Modern ES6 Way
// Variables are assigned based on their POSITION
const [car, truck, suv] = vehicles;
console.log(car); // 'Mustang'
console.log(truck); // 'F-150'Skipping and Rest
javascript
const scores = [100, 95, 80, 75, 60];
// Leave commas to skip elements!
const [first, , third] = scores;
console.log(third); // 80
// Combine with Rest Parameter
const [winner, ...losers] = scores;
console.log(losers); // [95, 80, 75, 60]Common Pitfalls
- Assuming array destructuring works by name like Object destructuring. Array destructuring is strictly position-based.
const [second] = arr;will NOT get the second item, it will get the FIRST item and simply name the variablesecond.
Interview Questions
Q:
How do you swap the values of two variables without using a temporary third variable?
A:
Using array destructuring! You can write: [a, b] = [b, a];. This unpacks the values into each other instantly.
Real-World Example
React's useState hook returns an array containing two items (the state value, and the setter function). We always destructure it immediately.
example
javascript
const [count, setCount] = useState(0);Check Your Knowledge
Test your understanding of Destructuring with these quick questions.