-1

I am currently going through the javascript track on codeacademy.com.

The current lesson asked me to do this, which will print out the value of each property:

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 p in nyc){
    console.log(nyc[p]);
}

All very straight-forward. But my question is, why does this not work when I use dot notation inside the for-loop? Like this:

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

Instead of printing out the 4 property values, it prints out the word 'undefined' four times. It seems illogical to me that I shouldn't be able to access the property using the dot notation also. If this isn't some peculiarity of the codeacademy lesson, then could someone please explain this to me?

Totem
  • 7,189
  • 5
  • 39
  • 66

1 Answers1

2

Because nyc.p is equivalent to nyc["p"], and presumably the object has no p property.

a.b in JavaScript is equivalent to a["b"], and is simply syntactic sugar. The only way to look up properties by a variable name is to use the bracket notation, because the dot notation always refers to a constant hard-coded property name.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • Are you saying the dot notation can only reference an object property that is a constant? – Totem Oct 28 '14 at 02:07
  • 1
    @Totem I say as much in my answer, yes. ;) And it can't be used to look up all property names. For example, you can do `a["*()-"]` but obviously you can't do `a.*()-`. It's just a shorthand notation for accessing properties with mostly-alphanumeric names that you know ahead of time. If you don't know the property name ahead of time (or want to use some looping structure to look up the property names in e.g. an array, to avoid code duplication), or the property name isn't also a valid JavaScript identifier, you need to use bracket syntax. – cdhowie Oct 28 '14 at 02:09