Array Destructuring
Unpack array items into separate variables.
Syntax
let [a, b] = array;Destructuring lets you pull items out of an array into individual variables in one line.
Skipping and rest
- Leave a gap with a comma to skip an item.
- Use
...restto gather the remaining items into a new array.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Unpack latitude and longitude from a coordinates array returned by a geolocation API.
- Extract the first and second elements from a useState hook return value in React.
- Swap two variables cleanly using array destructuring without a temporary variable.
More examples
Basic array destructuring
Unpacks latitude and longitude from a two-element array into named variables.
const coords = [40.7128, -74.0060];
const [lat, lng] = coords;
console.log(lat, lng); // 40.7128 -74.006Skip elements with commas
Uses a comma with no variable name to skip the green channel and extract only red and blue.
const rgb = [255, 128, 0];
const [red, , blue] = rgb;
console.log(red, blue); // 255 0Swap variables without temp
Swaps two variables in a single statement using array destructuring assignment.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
Discussion