In this lesson, we will analyze the operation destructuring of arrays. This operation is intended for bulk writing of array elements to variables in one line of code.
The syntax for this operation is as follows:
let [variable1, variable2, variable3] = array;
As you can see, variable names are listed
in square brackets to the left of the
=
sign. These variables are declared
in bulk through let
, which is placed
before the opening brace.
As a result of the operation, the first element of the array (that is, with the key zero) will be written to the first variable, the second to the second variable, and the third to the third variable.
Let's look at a practical example. Let's say we have an array that holds the year, month, and day:
let arr = [2025, 12, 31];
Let's write the year, month and day into the appropriate variables using destructuring:
let arr = [2025, 12, 31];
let [year, month, day] = arr;
Let's look at the contents of our variables:
console.log(year); // shows 2025
console.log(month); // shows 12
console.log(day); // shows 31
For comparison, see how awkward and long the code without destructuring will turn out:
let arr = [2025, 12, 31];
let year = arr[0];
let month = arr[1];
let day = arr[2];
console.log(year); // shows 2025
console.log(month); // shows 12
console.log(day); // shows 31
In the following code, parts of the array are written to the corresponding variables:
let arr = ['John', 'Smit', 'development', 'programmer', 2000];
let name = arr[0];
let surname = arr[1];
let department = arr[2];
let position = arr[3];
let salary = arr[4];
Rework this code through destructuring according to the learned theory.