Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
208,481 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
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
208,481 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.