Vivek Agrawal21
Vivek Agrawal21

Reputation: 332

JavaScript:strange behavior of Objects

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?

Upvotes: -1

Views: 66

Answers (3)

Niccolò Campolungo
Niccolò Campolungo

Reputation: 12042

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.

Upvotes: 4

Mumthezir VP
Mumthezir VP

Reputation: 6541

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.

Upvotes: 0

edi9999
edi9999

Reputation: 20554

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

Upvotes: 0

Related Questions