What is troubling you?
In what I wrote (in first code block I provided, console.log(property);), we will get all the properties of our object (property names only).
What part is troubling you? Why are we getting property names? How to get property values? What is this strange for loop doing?
Just write down what’s troubling you and I’ll try to provided very detailed answer, with some simple code examples.
It says to put all of the property values, yet I only put one property and they all get printed. I don’t understand why that happens. Sorry for being so confusing; I am very confused myself. @igorcaletacar
Ok, let me try it explain it this way.
Line for (var property in nyc) will get property names inside nyc variable.
So eventually we will have property = fullName, property = mayor, property = population and property = boroughs. fullName will be after pass one, mayor after pass two etc.
Now to print the property names, we would use console.log(property);.
But since we want the property values, we need to take the value of each of object properties. Since this object is represented by some properties and values, we can say he’s got key => value structure, where key is our property name.
So to get the values of our objects properties we need to use console.log(nyc[property]);.
Now for the first pass we will have property = fullName, so in console log we would have console.log(nyc[property]);. Since property is equal to fullName, we can say it’s actually printing console.log(nyc[fullName]);, which equals to New York City.
Second pass our property is property = mayor, so in console.log() we have console.log(nyc[mayor]);, which equals to Bill de Blasio.
Later we will be printing nyc[population] and nyc[boroughs].
SInce we wanted to print all of our objects properties values, we used for loop to get all properties. Then we just used those properties as keys when printing values for each property in console.
I hope it’s really clear for you now. Because I’m running out of explanations haha. Let me know if you have any more questions, I’ll try my best to explain it.
I appreciate the explanation as well! I didn’t realize that the property in for (var property in object) would be assigned each individual property associated with an object.
@igorcaletacar
I have a confuse question.
Normally, I will get the value of property of object like this object["property"]
but why this time we can use object[property]
to get the value.
I think the best thing to do would be to redirect you to this link. There are multiple ways you can access object properties, best thing to do is to pick one and stick to it, but you can mix them all up if you want.