Register to get access to free programming courses with interactive exercises

Destructuring JS: Arrays

Destructuring is the syntactic ability to unpack array elements (and more) into individual constants or variables. Destructuring is an optional feature but very nice to have. Let's look at some examples.

Imagine that we have an array of two elements that we want to operate on in our program. The easiest way to use its elements is to always refer to the index point[0] and point[1].

const point = [3, 5];

console.log(`${point[0]}:${point[1]}`); // => 3:5

Indexes tell you nothing about the content, and you'll have to make extra effort to understand this code. It is much better to first assign these values to variables with good names. Then the code will become readable:

const x = point[0];
const y = point[1];

console.log(`${x}:${y}`); // => 3:5

This code is much clearer, although longer. With destructuring, the same thing can be shortened:

const [x, y] = point;
// The left array repeats the structure of the right array
// but identifiers are used instead of values
// they are filled with values at the same positions in the right array
// [x, y] = [3, 5]
// x = 3, y = 5

console.log(`${x}:${y}`); // => 3:5

It's both shorter and clearer (especially if you get used to this way of writing). Destructuring allows you to extract almost any part of an array using a very short and intuitive syntax. It works even if we are only interested in part of the array. Both the beginning and the end:

// Retrieve the first element
// The rest are ignored
const [x] = point;

// Retrieve the second element
// To do this, all you need to do is not specify the first element
const [, y] = point;

// or
const [, secondElement, , fourthElement, fifthElement] = [1, 2, 3, 4, 5, 6];

console.log(secondElement); // => 2
console.log(fourthElement); // => 4
console.log(fifthElement);  // => 5

https://repl.it/@hexlet/js-arrays-destructuring-positional

We retrieved from the array [1, 2, 3, 4, 5, 6] the values of the second, fourth, and fifth elements, storing them in the secondElement, fourthElement and fifthElement constants, respectively. At the same time, in the place of the first (zero index) and the third (second index) elements, we made gaps without specifying any variables because in this case, we didn't need the values of these elements.

If you specify a variable during destructuring in such a way that no array element corresponds to it, the variable will be written to undefined:

const [firstElement, secondElement, thirdElement] = [1, 2];

console.log(firstElement);  // => 1
console.log(secondElement); // => 2
console.log(thirdElement);  // => undefined

The original array consists of only two elements, so the thirdElement retained undefined. But in such cases, you can define a default value as insurance:

const [firstElement, secondElement, thirdElement = 3] = [1, 2];

console.log(firstElement);  // => 1
console.log(secondElement); // => 2
console.log(thirdElement);  // => 3

There is no match for thirdElement in the [1, 2] array, so a default value of 3 was written to the thirdElement constant.

Destructuring works at any nesting level. For example, you can use it to extract data from arrays within arrays:

const [one, [two, three]] = [1, [2, 3]];

The number of possible combinations and uses of destructuring is endless. The more you experiment with it, the more you will find options for its use.

Destructuring in loops

Array unpacking can be used not only as a separate instruction in code but also, for example, in loops:

const points = [
  [4, 3],
  [0, -3],
];

for (const [x, y] of points) {
  console.log([x, y]);
}

// => [ 4, 3 ]
// => [ 0, -3 ]

https://repl.it/@hexlet/js-arrays-destructuring-for-of

In fact, this unpacking can be done anywhere an array is explicitly or implicitly expected. You're bound to come across input parameters, function return values, loops, and plenty of other situations.

const swapValues = ([a, b]) => [b, a];

swapValues([1, 2]); // [2, 1]

Destructuring strings

In JavaScript, strings behave like arrays and can also be restructured.

const [first, second, third] = 'two';
console.log(first); // => 't'
console.log(second); // => 'w'
console.log(third); // => 'o'

Recommended materials

  1. Documentation

Hexlet Experts

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

About Hexlet learning process

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions

Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.