-2
var me = new Object();
me.name = "Adithya";
me.age = 15;

for(var prop in me){
    console.log(me.prop); 

}

When I run this, it prints undefined. I don't understand why it doesnt print the value. When I type

console.log(prop);

it prints

name
age

Doesn't that mean that prop is a a field in me? So shouldn't me.prop(when prop is name) , work like me.name ?

SocketPhys
  • 45
  • 6
  • [MDN - `for / in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Examples). – Felix Kling Oct 10 '15 at 01:53

2 Answers2

2

The syntax you're looking for is me[prop];
me.prop is equivalent to me['prop'] which is not what you want.
notice you didn't assign a value to name or age before when you did me.age and me.name.

Musa
  • 96,336
  • 17
  • 118
  • 137
2

prop is a variable containing a string so you need to use me[prop] like this:

for(var prop in me){
    console.log(me[prop]); 
}

When your property name is in a variable, you need to use the [prop] syntax which in your case would be me[prop].


FYI, me.prop tries to access a property named "prop". It does not use the contents of the variable prop. You can only use the dot syntax to access a property when the property name is a constant that is known at code parse time and when the characters in the property are legal to use in the Javascript dot syntax. If it's in a variable (or if it contains characters like a . or a space), then you must use the bracket syntax which will fetch the contents of the variable and use that property name.

jfriend00
  • 683,504
  • 96
  • 985
  • 979