Destructuring Arrays
Unpacking.
When you want the first few items of an array in their own variables, you could write one line for each. Destructuring does it in one line, by matching positions.

- First few items
- One line each?
- Destructuring
Matching positions
Square brackets on the left side of equals unpack by position. First gets the first item, and second gets the second. A comma skips an item. Rest collects whatever is left. And there's a neat trick for swapping two variables. Run it.
const podium = ["Ana", "Ben", "Cara", "Dev", "Eli"];
const [first, second] = podium;
console.log(first, second);
const [gold, , bronze, ...others] = podium;
console.log(gold, bronze, others);
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);Ana Ben Ana Cara [ 'Dev', 'Eli' ] 2 1
Where you will see it
Destructuring appears all over modern JavaScript. In loops with entries, in functions that return several values as an array, and in frameworks like React. You can also give a default value, in case an item is missing, with an equals sign.
| key | value |
|---|---|
| [a, b] = arr | by position |
| [a, , c] | skip one |
| [a, ...rest] | the rest |
| [a = 0] | a default |
Swapping and skipping
Destructuring has some neat tricks. You can swap two variables in one line, without a temporary variable. A comma with nothing before it skips an item. And rest collects whatever's left over into a new array. Run it.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b);
const [, second, , fourth] = ["w", "x", "y", "z"];
console.log(second, fourth);
const [winner, ...others] = ["Ana", "Ben", "Cara"];
console.log(winner, others);2 1 x z Ana [ 'Ben', 'Cara' ]
Summary
Array destructuring unpacks items into variables by position, with skips, rest, and defaults. Next, practice with a shopping cart.
Key takeaways- const [a, b] = arr
- Skip with commas
- Swap with [x, y] = [y, x]