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

Explain how this code works.

var nyc = { fullName: "New York City", mayor: "Bill de Blasio", population: 8000000, boroughs: 5 };

for (var x in nyc) { console.log(nyc[x]); }

This is from another site, i wont name but i dont understand how if i do:

for (var x in nyc) { console.log(nyc[x]); }

it returns the values from nyc, but if i do:

for (var x in nyc) { console.log(x); }

it will return the keys. Can someone explain to me how x works and why the [x] pulls out nyc's values instead of key names.

2 Answers

Hi Connor

I think x takes the key from object nyc when you do var x in nyc

And, in Javascript when you want to take the value from the object

you do variableName[key] = value

As x is a key, so [x] will return the value of the key x.

Do you get what I mean?

So does the bracket basically do the same function as a array? it is pulling any strings that the key holds?

Where as no brackets mean i will just get the name of the key. Hope i didnt make it even more complicated haha, but i think i understand it more now.

You really asked a complicated question haha, but I'll try to answer it.

So does the bracket basically do the same function as a array?

Yes, it does. We use index number between the bracket to get the value from the array.

it is pulling any strings that the key holds?

Yes, it is.

You recommend you to google and read more about array vs object javascript.

You will get more understanding. Good luck. :D