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.
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'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]const [second] = arr; will NOT get the second item, it will get the FIRST item and simply name the variable second.How do you swap the values of two variables without using a temporary third variable?
Using array destructuring! You can write: [a, b] = [b, a];. This unpacks the values into each other instantly.
React's useState hook returns an array containing two items (the state value, and the setter function). We always destructure it immediately.
const [count, setCount] = useState(0);Test your understanding of Destructuring with these quick questions.
Question 1
In `const [a, b] = [10]`, what is the value of `b`?
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.
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'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]const [second] = arr; will NOT get the second item, it will get the FIRST item and simply name the variable second.How do you swap the values of two variables without using a temporary third variable?
Using array destructuring! You can write: [a, b] = [b, a];. This unpacks the values into each other instantly.
React's useState hook returns an array containing two items (the state value, and the setter function). We always destructure it immediately.
const [count, setCount] = useState(0);Test your understanding of Destructuring with these quick questions.
Question 1
In `const [a, b] = [10]`, what is the value of `b`?