Variables can have default values. In
this case, if the array element is
absent for the variable, the default
value will be taken. In the following
example, the variable day
defaults to 1
:
let arr = [2025, 12];
let [year, month, day = 1] = arr;
console.log(year); // shows 2025
console.log(month); // shows 12
console.log(day); // shows 1
But if there is a value in the array
for the variable day
, the
default value will be ignored:
let arr = [2025, 12, 31];
let [year, month, day = 1] = arr;
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'];
let name = arr[0];
let surname = arr[1];
let department = arr[2];
let position;
if (arr[3] !== undefined) {
position = arr[3];
} else {
position = 'trainee';
}
Rework this code through destructuring according to the learned theory.