0

I'm trying to access the properties of this object:

var obj = {hello: 1, world: 2};

This gives me back undefined:

function foo(a) {
  for(property in a) {
    console.log(a.property);
  }
  return "foo";
}

foo(obj);

This gives the intended result:

function bar(a) {
  for(property in a) {
    console.log(a[property]);
  }
  return "bar";
}

bar(obj);

Why does the call to foo not work, while the call to bar allows me to access the properties?

Zack Gao
  • 568
  • 1
  • 4
  • 14
  • 1
    possible duplicate of [JavaScript property access: dot notation vs. brackets?](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) –  Jan 20 '14 at 22:37
  • 1
    ...because there's no property called `property`? – tckmn Jan 20 '14 at 22:38
  • @TimCooper : Tangentially related, that link seems to discuss best practice, whereas I think the OP is asking for an explanation of why he gets an undefined when he uses the (obviously) wrong syntax. – Jason M. Batchelor Jan 20 '14 at 22:46

1 Answers1

5

Because a.property is the same as a['property'], not a[property]. So you actually try to access the property "property".

Your second code snippet uses the variable property, the former uses the property property.

Tobias
  • 7,723
  • 1
  • 27
  • 44