List ALL the Properties! clarification


#1

So I was just hoping for clarification on a part of the exercise "List ALL the Properties!" My code worked fine, I was able to get through it and figure it out easily, but I don't understand the why aspect. So the lesson states that to access and print all of the properties, you set "var a" (or variable name of your choosing) to the property, like fullName below. Then you use a for loop to access it and it prints all of the values.

What I'm not understanding is : if you set a variable equal to a property, then reference that variable in the for loop, why does it print each value instead of just the one that you set the variable equal to?


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
var a = "fullName";
for (var a in nyc) {
    console.log(nyc[a]);
}


#2

I think you have a little flaw.

If you use a for in loop you iterates over all properties of this object.

for (var a in nyc){ 
//  var a is now the property key 
console.log("Key: " + a + " with value: " + nyc[a]); 
// first a = fullName
// second  a = mayor
// third a = population 
// and so on 
}

This line var a = "fullName"; is not necassary

Read for ... in
and Object literals

For one value you can type

console.log(nyc.fullName);

or

console.log(nyc['fullName']);

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.