A.Arya
A.Arya

Reputation: 1

issue in accessing javascript object on looping

In for..in loop,

Why does the value of a property when accessed as o.i returns undefined however o[i] returns the correct value?

Code snippet for reference:

var object = {
   id:2,
   name:'axs',
   address:'colon street'
};

for(let property in object){
  console.log(object.property); // returns undefined
  console.log(object[property]); // returns property-value
}

Upvotes: 0

Views: 72

Answers (5)

user4793706
user4793706

Reputation:

The expression object.property returns undefined, because no property named property is found on object.

Upvotes: 0

JMP
JMP

Reputation: 4467

Because the dot notation sees property as a property of the object used. To use the 'property' from the for-in loop as a variable, you need to use the square bracket accessors.

If you give your object a 'property' property, it works as expected:

var object = {
   id:2,
   name:'axs',
   address:'colon street',
   property:'residential'
};

for(let property in object){
  console.log(object.property); // returns 'residential'
  console.log(object[property]); // returns property-value
}

Upvotes: 0

nkshio
nkshio

Reputation: 1080

In for..in loop, property is assigned to the variable as a string i.e inside the loop, typeof(i) will always return "string". MDN explanation on how for..in works.

When accessed with the dot notation, engine tries to read as o."name", which it correctly finds as undefined. Please note o.name and o."name" are 2 different things.

Accessing object's properties using

  • the dot notation - property must be a valid JavaScript identifier i.e. property will get evaluated to return the required value.

  • the bracket notation - property is always a string. The string does not have to be a valid identifier, it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

PS

When accessing object properties with for..in, Please note if you want to consider properties attached to the object only, and not its prototypes. In such a case use getOwnPropertyNames() or perform a hasOwnProperty() check. MDN explanation

Upvotes: 1

Terry Lennox
Terry Lennox

Reputation: 30705

They are different ways of accessing object properties. o.i is equivalent to o['i'], which in your case is not present, so undefined is returned.

Upvotes: 0

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

o.i will look for property i in the Object but when you do o[i] it looks for the evaluated property i which may be: name, id, etc...

While fetching properties with a dot notation, the variable is not evaluated, it is considered that you are trying to fetch the property i itself.

Upvotes: 4

Related Questions