Search code examples
javascriptloopsfor-in-loop

For In loop, why property value can't be accessed through obj.property?


var ni = {'hello': 23, 'he':'h', hao: 45};
for( var propertyName in ni) {
    console.log(ni[propertyName])  //23,'h',45
    console.log(ni.propertyName)   // undefined 3 times?
}

what is the reason ni.propertyName doesn't work here?


Solution

  • ni.propertyName is equivalent to ni["propertyName"]: it gets the value of a property literally named "propertyName". ni[propertyName] on the other hand uses your propertyName variable for the lookup.