Accessing object properties in javascript using for loop?

consider the following object:

var nyc = {
fullName: "New York City",
mayor: "Bill de Blasio",
population: 8000000,
boroughs: 5
};

when i try to access each of the properties using for loop:

for(var key in nyc){
console.log(nyc[key]);
}

it returns correct output(property values), but…

for(var key in nyc){
console.log(nyc.key);
}

this return “undefined” on 4 lines

Why the strange behavior, since both:

console.log(nyc.fullName);
console.log(nyc['fullName']);

give same o/p.


Source: oop

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.