Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

This question already has an answer here:

below is a simple samlple, i wanna display the object properties using for/in loop

var Object = { x:1, y:2, z:3 };
for (property in Object) {
  console.log(Object.property);
};

it shows undefined.

but if using console.log(Object[property]); it works, and shows 1 2 3

why i cannot use Object.property to display in for/in loop?

share|improve this question

marked as duplicate by Mohsen, webnoob, shiplu.mokadd.im, Ian, Benjamin Gruenbaum Jun 11 '13 at 17:00

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5  
First, you would use Object[property]. Second, don't use "Object" as the variable's name - it's the object constructor, and may or may not mess up other things...**especially** if this code is in the global scope – Ian Jun 11 '13 at 16:52
up vote 5 down vote accepted

This has to do with notation and syntax

Object.property will give you undefined because you're accessing the property with the name property.

If you have this object:

var o = {
    property: "value",
    value: "foo"
};

o.property; // "value"
o["property"]; // "value" (equivalent)
o.value; // "foo"
o["value"]; // "foo" (equivalent)
o[o.property]; // "foo" no other notation possible

So in:

var Object = { x:1, y:2, z:3 };
for (property in Object) {
  console.log(Object.property);
};

The value of property is "x", "y" and then "z". But Object.property is equivalent to Object["property"]. Whereas Object[property] gives you Object["x"] etc.

share|improve this answer
    
thanks so much @Frits van Campen – Will Jun 11 '13 at 17:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.