1

consider the following object:

var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};

when i try to access each of the properties using for loop:

for(var key in nyc){
console.log(nyc[key]);
}

it returns correct output(property values), but...

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

this return "undefined" on 4 lines

Why the strange behavior, since both:

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

give same o/p.

purudpd
  • 169
  • 2
  • 15
  • possible duplicate of [JavaScript property access: dot notation vs. brackets?](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Kyll Jul 18 '15 at 08:18
  • @Kyll: No, that's asking for reasons to use one or the other, explicitly "other than the obvious" that you can use a variable with one of them. I'm sure there's a dupe (dozens, probably, all subtly different), but that's not it. – T.J. Crowder Jul 18 '15 at 08:22
  • But don't the answers there actually answer this question? I [read on Meta](https://meta.stackoverflow.com/questions/297422/how-to-handle-questions-whose-root-cause-is-an-already-well-answered-issue) that I should flag as a dupe for the sake of the answer, not of the question. – Kyll Jul 18 '15 at 08:24
  • @Kyll: I'd say no, they talk about reasons for using one or the other, not the fundamental. (In particular the accepted/upvoted one.) But it's probably a judgment call. I'm sure there's a good original out there to point this at, though. If not, this is one of the purest versions of this question I've seen, it could become the canonical one. (But there must be one.) – T.J. Crowder Jul 18 '15 at 08:28
  • Then, if something more specific is needed, https://stackoverflow.com/questions/20736758/difference-between-dot-notation-and-bracket-notation-in-javascript should do the trick no? Already spent my flag though. – Kyll Jul 18 '15 at 08:32

1 Answers1

5

nyc.key looks for the property with the name key, not the property with the name in the variable key. Your first example, nyc[key], is the correct way to use the property name from the variable.

In JavaScript, you can access object properties using dot notation and a property name literal (obj.foo), or brackets notation and a property name string (obj["foo"]). In that second case, you can use any expression to get the string, including a variable lookup. (In ES6, you can also use Symbols with brackets notation, but it's not relevant here.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875