Array Destructuring

Unpack array items into separate variables.

Syntaxlet [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 ...rest to gather the remaining items into a new array.

Example

Try it yourself
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.

Example · js
const coords = [40.7128, -74.0060];
const [lat, lng] = coords;
console.log(lat, lng); // 40.7128 -74.006

Skip elements with commas

Uses a comma with no variable name to skip the green channel and extract only red and blue.

Example · js
const rgb = [255, 128, 0];
const [red, , blue] = rgb;
console.log(red, blue); // 255 0

Swap variables without temp

Swaps two variables in a single statement using array destructuring assignment.

Example · js
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1

Discussion

  • Be the first to comment on this lesson.