Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Array Destructuring

Array destructuring lets you unpack values into variables in a clean, readable way.

It is especially useful for function returns and swapping values.

Why We Need It

Destructuring reduces repeated indexing and makes intent clear.

It also works well with rest syntax and default values.

Syntax

const [a, b] = array
const [first, , third] = array
const [head, ...tail] = array

Basic Example

1. Basic destructuring

const coords = [10, 20];
const [x, y] = coords;

console.log(x, y);

Assign positions to variables.

Real World Example

2. Skip items

const items = ["a", "b", "c"];
const [first, , third] = items;

console.log(first, third);

Use commas to skip.

Multiple Use Cases

Unpack Values

Destructuring lets you unpack array values into variables.

It improves readability compared to manual indexing.

Skip and Defaults

You can skip elements with commas and set default values.

This is useful for optional positions.

Rest Elements

Use rest syntax to collect remaining items into a new array.

Rest must be the last element in the pattern.

More Examples

3. Defaults

const list = ["only"];
const [a, b = "default"] = list;

console.log(a, b);

Provide defaults for missing values.

4. Rest

const nums = [1, 2, 3, 4];
const [head, ...tail] = nums;

console.log(head, tail);

Collect remaining items into a new array.

Comparison

Without

const first = items[0];
const second = items[1];

With

const [first, second] = items;

Common Mistakes and Fixes

Assuming value exists

Use defaults for optional positions.

Rest not last

Rest must be the final pattern element.

Overusing destructuring

Keep code readable; use destructuring when it helps.

Interview Questions

How does destructuring work?

It assigns values by position from the array.

Can you set defaults?

Yes, use = defaultValue in the pattern.

Where must rest appear?

At the end of the destructuring pattern.

Practice Problem

Practice: Destructure a list of three colors into variables.

const colors = ["red", "green", "blue"];
// TODO: destructure into a, b, c

One Possible Solution

const colors = ["red", "green", "blue"];
const [a, b, c] = colors;
console.log(a, b, c);

Frequently Asked Questions

What does array destructuring do?

It assigns array items to variables by position.

Can I skip items?

Yes, by leaving a blank spot between commas.

How do I capture the rest?

Use ...rest as the last pattern element.

Try It Yourself

Try skipping values or adding defaults.