0

A similar question is asked, but it didn't meet the conditions I've met.

I know that to access a property I can use either point notation or bracket notation. An article at jibbering.com states the same, also this answer. The Specifiacation says the same.

I have this example ( fiddle ) and there is a difference:

var utils = {
    myString: "boo",
    myNumber: 99,
    justNULL: null
};

for (var i in utils) {
    document.write ( i + " = " + utils.i + "<br/>" ); //result - undefined
    document.write ( i + " = " + utils[i] + "<br/>" );//result - the actual value
}​

What I am missing here? Is it something about the usage of the for..in or the definition of the object?

1
  • The member access operator (the dot) is slightly different... Anything that follows it must be a valid JavaScript identifier. So, for example, obj.foo = 'bar'; works, but obj.123 = 'bar'; does not, because identifiers can't start with a number. However, obj['123'] = 'bar'; works. Commented Apr 16, 2012 at 6:51

2 Answers 2

1

No, it's the usage of the point notation that is the problem.

You can't use a variable for the property name when you are using the point notation. The expression utils.i will access the property i in the object, it won't use the variable i for the name.

Sign up to request clarification or add additional context in comments.

1 Comment

O, I didn't thought about this. 10x :)
1

You need to use utils[i] format here because i is a string and a string reference can not be used to access a property using the use object.property format.

var obj = {};
obj.foo = 'test';

obj.'foo' // doesn't work
obj['foo'] // works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.