-1
var person={fname:"John",lname:"Doe",age:25};
person.fname; //it gives a output John
for (x in person)
 {
 alert(person[x]); //works fine
 person.x; //incorrect why???
 }

Can someone please explain the exact logic behind this?

asked Jul 16, 2013 at 9:31
2
  • 2
    person.x works the exact same way as person.fname (which you seem to be okay with) Commented Jul 16, 2013 at 9:33
  • I think it might be better if you also explain why you considered the behaviour to be strange and "person.x" to be incorrect, so that other JavaScript learners that stumbled upon this question can learn from your experience. Commented Jul 16, 2013 at 9:44

3 Answers 3

4
var person = {fname:"John", lname:"Doe", age:25};
for (var x in person) {
 alert(person[x]); 
}

In the loop x assumes three different values: fname, lname and age. By doing person[x] you're trying to access three different properties. It's like doing person['fname'], person['lname'] and person['age']. They are the same thing to person.fname, person.lname and person.age, which are defined properties of the person object. If you do person.x you're trying to access an undeclared property x which correctly returns undefined.

The usage of [] is also known as bracket notation, which is needed in the case of iterations and other things, like setting a dynamic property to an object given by user input(for example), but they have a large usage range.

Ian
51k13 gold badges104 silver badges111 bronze badges
answered Jul 16, 2013 at 9:35
Sign up to request clarification or add additional context in comments.

Comments

0

This is because Javascript can't decide if you want to access the x property of object person (for example if person={x:100,y:65}), or the property that is the value of the string x.

  • person[x] will evaluate x to it's value
  • person.x will take the property x
answered Jul 16, 2013 at 9:39

Comments

0

person.fname will give you fname object of person object.

person.lname will give you lname object of person object.

person.age will give you age object of person object.

for (x in person)
 {
 alert(person[x]); 
 }

it'll iterate through the person object. While in person.x; 'x' is an unknown property to person object.

It is better you should go through some basic javascript concepts, here and here.

answered Jul 16, 2013 at 9:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.