JavaScript Introducing ES2015 Objects and New Collection Types Map

Why does he use [0] and [1] in his for of loop?

Can someone explain the index numbers in the for of loop? I can't figure out why he is using numbers to begin with instead of i, and then he uses two different numbers to refer to the same student. Thank you for taking the time!!

3 Answers

Steven Parker
Steven Parker
177,955 Points

It looks like the video is giving a demonstration of how each element in a Map can be accessed as an array of two elements, with the first ([0]) being the key and the second ([1]) being the value (which in this case is an object with student data).

I didn't realize that could seem awkward until you pointed it out. I think it might be clearer to employ a destructuring assignment to extract both parts and then use them without indexing, as in this revision of the video example:

for (let [key, data] of classroom) {
  console.log(`'${key}': ${data.name] is ${data.age} |`);
}

Steven, Thanks! That makes perfect sense now.

Van Tran Huu
Van Tran Huu
16,248 Points

This explanation is simply clear enough!

Robert Gouveia
PRO
Robert Gouveia
Pro Student 1,713 Points

using a 0 and a 1 like this:

var cars = {'Ford': 'Fiesta','Nissan': 'Skylander','Vauhall': 'Zafira'}
var endText = '';
foreach(cars as car){
endText += 'Make Of Car: ' +  car[0] + ' - Model Of Car: ' + car[1] ' <br>';
}

Think of it like this, the first is the Make of the car (KEY) and the other is the model of the car (Value).

Its an array with 2 indexes which is shown in the above code.

Hope this helps

Steven Parker
Steven Parker
177,955 Points

Are you sure that's JavaScript? I've never seen this syntax before:

foreach(cars as car){

Also the "cars" in that example is an ordinary object and not a Map, so the keys and values cannot be extracted using indexing.

Robert Gouveia
PRO
Robert Gouveia
Pro Student 1,713 Points

Its php but it's the same context, for the jquery version you can checkout this .each loop

The point was not the loop it was just an example to what the 0 and 1 meant :)