CodeBlanks Logo Icon CodeBlanks

Array destructuring

JavaScript course · Advanced · Lesson 25/100

Learn to extract array elements into variables in order.

Array destructuring

Destructuring works on arrays too, but you use square brackets because order matters. When you write const [first, second] = colors, colors[0] goes to first and colors[1] goes to second.

The array index is independent of the variable name. You could write red instead of first; the value is still colors[0]. Order is purely positional.

Skipping elements

To skip an element in an array, leave its position empty between commas. With const [first, , third] = colors you take the first and third colors and skip the second.

An empty comma consumes one position; the element between two commas is ignored. This saves you from slicing the array when you only want a few elements.

Exercise Take the first and third color

Create an array called colors with at least three colors. Use destructuring to pull the first and third colors into first and third variables (skip the second). Then log each one separately with console.log.

Show example solution
const colors = ["red", "blue", "green"];
const [first, , third] = colors;
console.log(first);
console.log(third);

Test yourself

  1. In `const [a, b] = [10, 20]`, what is `b`?

    • 20
    • 10
    • [10, 20]
    • undefined
    Show answer

    20 — Correct. `b` takes the second element of the array, which is 20.

  2. Skip the second color

    const colors = ["red", "blue", "green"];
    const [first, , third] = ____;
    console.log(first, third);
    Show answer
    const colors = ["red", "blue", "green"];
    const [first, , third] = colors;
    console.log(first, third);
  3. How do you skip the second element of an array?

    • Write `skip` as the second variable
    • Use an object instead of an array
    • Leave a comma with no variable in the second position
    • Set the second variable to `null`
    Show answer

    Leave a comma with no variable in the second position — Correct. The empty comma in `[first, , third]` skips the second element.

  4. Match the concepts

    array destructuring
    Extract by order with square brackets
    empty comma
    Consumes a position, skips an element
    position
    Tied to the index order

All lessons in Advanced