You can use array destructuring to extract individual values from an array and put them in new variables.
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
first
, second
, and third
variables are filled with 5
, 10
, and 15
as values.first
, second
, fourth
variables are filled with 5
, 10
, 20
as values.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.sixth
variable is set as undefined because array [5] does not exist.sixth
is set to 30
.agesFun
method returns the array so first
to fifth
variables are set to 5
, 10
, 15
, 20
and 25
.RELATED TAGS
CONTRIBUTOR
View all Courses