ES6 - Use Destructuring Assignment to Assign Variables from Arrays

I don’t understand why:

c = 5

In the example it says:

The variable a is assigned the first value of the array, and b is assigned the second value of the array. We can also access the value at any index in an array with destructuring by using commas to reach the desired index:

const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c);

The console will display the values of a , b , and c as 1, 2, 5 .

Wouldn’t c = 3 and e = 5?

Challenge: ES6 - Use Destructuring Assignment to Assign Variables from Arrays

Link to the challenge:

Where do you see the variable e in the following?

const [a, b,,, c] = [1, 2, 3, 4, 5, 6];

Ah, I see now :upside_down_face:

The "," esentially shifts "c" along the index of the array thus assigning it to that index depending how many "," there are.

If the "," exceeds the .length of given array, it will return undefined.

Hi there and welcome to our community!

I can see why this may be confusing but it’s working on the false premise that the numerical values in the array would automatically correlate with an arbitrary alphabetical sequence.

This could also have been written as:

const [banana, helicopter,,, giraffe] = [1, 2, 3, 4, 5, 6];
console.log(banana, helicopter, giraffe);

…which would produce exactly the same output.
The point is that you assign variable names to elements of the array and by using commas in this way, you skip array elements, so c (or giraffe) is assigned the value of the 5th element in the array, because the 3rd and 4th values are skipped.

1 Like

Thank you. I miss read the point about the commas.

Makes sense now.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.