Lesson 19 / 38
Destructuring Arrays & Objects
Unpack values from arrays and objects in one line.
Array destructuring
Positions matter — you can skip items with an empty slot, and even swap variables in one line.
const [first, second, , fourth] = [10, 20, 30, 40];
console.log(first, second, fourth); // 10 20 40
let [a, b] = [1, 2];
[a, b] = [b, a]; // swap
console.log(a, b); // 2 1Object destructuring
Names matter here, not order — and you can set a default for missing keys.
const { name, age } = { name: "Ada", age: 36 };
console.log(name, age);
const { city = "Unknown" } = {};
console.log(city); // UnknownRenaming while destructuring
const { name: fullName } = user; pulls name out into a variable called fullName.
Quick check: What does `const [a, , b] = [1, 2, 3]` set b to?
- 2
- 3
- undefined
Answer
3 — The empty slot skips index 1, so b picks up index 2, which holds 3.