10. List ALL the properties


#1

I am not sure I understand why this does not work.

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

What is the difference with the above code and writing this?

console.log(nyc[property]);

Would really appreciate an easy explanation!!


#2

The first code is used to iterate through all of the properties of object. Second snippet is used to get value of only one, specified property.

Exemplary code:

function Person(name, age, country) {
    this.name = name;
    this.age = age;
    this.country = country;
}

var me = new Person("Maciej", 23, "Poland");

// iterate through all properties of me object
for (var property in me) {
    console.log(property + ": " + me[property]);
}

// get specific information (value of specific property)
console.log(me["country"]);
// or...
console.log(me.country);

#3

First code: for (var property in nyc)-->means "nyc" is assigned to a new variable "property." That is, each "for" loop runs, one by one property in nyc is assigned to the new variable "property." So you just need print the new variable => console.log(property); // this will only print the property names:fullName, mayor, population, boroughs.

Second code: console.log(nyc[property]); ==>// print the values associated with every property name: New York City, Bill de Blasio, 8000000, 5

Hope my explanation help you!


#4

See this:
JavaScript property access: dot notation vs. brackets?