Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
231,236 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.

This explanation is simply clear enough!

Robert Gouveia
PLUS
Robert Gouveia
Courses Plus Student 1,714 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 :)

Robert Gouveia
PLUS
Robert Gouveia
Courses Plus Student 1,714 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
231,236 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.