10/30 - Why doesn't dot notation work?


I don't understand why I can't use dot notation for the line in bold. It only works with the bracket notation. Can someone explain to me in a SIMPLIFIED manner why that is the case?

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 key in nyc)
console.log(nyc.key); //this does not work
console.log(nyc[key]); //this does work


Dot notation is property specific, meaning the key name must be defined already if it is being looked up. key is not a property that exists, but a variable that refers to a property name. In other words it is dynamic and can refer to any property in the object.

for (var key in nyc)

Here key is a placeholder. The in operator binds it to one property at a time so that it can be enumerated.


prints the values associated with fullName, mayor, population and boroughs as in,



Thanks so much for the prompt response and much more importantly, a clear & understandable answer. cheers!


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