10. List ALL the Properties!


#1

Hey, got a question regarding this lesson. Here's my code:

var nyc = {
    fullName: "New York City",
    mayor: "Bill de Blasio",
    population: 8000000,
    boroughs: 5
};
// write a for-in loop to print the value of nyc's properties
for(var x in nyc) {
    console.log(nyc[x]);
}

Why don't I have to declare what var x is?
How does JavaScript know that x is referring to all the properties in my object "nyc"?


#2

Actually, you have declared what var x is, the iterator variable of a for..in statement. It is a reference to each property name (key) in the object, a different one with each iteration.

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

When key is fullName, nyc[key] is nyc['fullName'] which is, "New York City". The rest follow suit in similar fashion.


#3

Thanks, mtf. I think I get it. So the for in loop makes sure, that the variable in the condition is seen as a representative of all my properties in the declared object?


#4

'representative' is a good word to describe it.