AI Hints
Home›JavaScript Tutorial›Modern Array Tools
JavaScript · Lesson 54 of 138

Destructuring Arrays

Unpacking.

⏱ 2 min read▶ Video at 1:05:50🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Destructuring Arrays
From the video: Destructuring Arrays
  • 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.

app.jsjavascript
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);
Output
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.

keyvalue
[a, b] = arrby 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.

app.jsjavascript
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);
Output
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]
Next up: Practice: A Shopping Cart — arrays in action