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, and third variables are filled with 5, 10, and 15 as values.
  • In Example 2, first, second, fourth variables are filled with 5, 10, 20 as values.
  • In Example 3, first and second variables are filled with 5 and 10 as values, and the rest of the values are filled in the remaining variable [15, 20, 25] as an array.
  • In Example 4, the sixth variable is set as undefined because array [5] does not exist.
  • In Example 5, sixth is set to 30.
  • In Example 6, the agesFun method returns the array so first to fifth variables are set to 5, 10, 15, 20 and 25.

Free Resources