What is array destructuring in Javascript?
You can use array destructuring to extract individual values from an array and put them in new variables.
Code
let ages = [5, 10, 15, 20, 25],first, second, third, fourth, fifth, sixth;function agesFun(){return ages;}// Example 1[first, second, third] = ages;console.log(first, second, third); // 5, 10, 15// Example 2[first, second, ,fourth] = ages;console.log(first, second, fourth); // 5, 10, 20// Example 3[first, second, ...remaining] = ages;console.log(first, second, remaining); // 5, 10, [15, 20, 25]// Example 4[first, second, third, fourth, fifth, sixth] = ages;console.log(first, second, third, fourth, fifth, sixth); // 5, 10, 15, 20, 25, undefined// Example 5[first, second, third, fourth, fifth, sixth] = ages;console.log(first, second, third, fourth, fifth, sixth = 30); // 5, 10, 15, 20, 25, 30// Example 6[first, second, third, fourth, fifth] = agesFun();console.log(first, second, third, fourth, fifth); // 5, 10, 15, 20, 25
Explanation
- In Example 1,
first,second, andthirdvariables are filled with5,10, and15as values. - In Example 2,
first,second,fourthvariables are filled with5,10,20as values. - In Example 3,
firstandsecondvariables are filled with5and10as values, and the rest of the values are filled in theremainingvariable[15, 20, 25]as an array. - In Example 4, the
sixthvariable is set as undefined because array [5] does not exist. - In Example 5,
sixthis set to30. - In Example 6, the
agesFunmethod returns the array sofirsttofifthvariables are set to5,10,15,20and25.