1

I'm working my way through a tutorial and I have hit a snag.

I created this object and I'm trying to loop through and print the first names of the entries. I thought it was working, but then I noticed that when I change 'firstName' in my for loop to 'number' or 'lastName', it still writes the first names to the console.

Can anyone shed some light for me? Thanks!

var friends = {
  bill:{
    firstName:"Bill",
    lastName:"Gates",
    number:"617-333-3333",
    address:["One Microsoft Way", "Redmond", "WA", "98052"]
  },
  steve:{
    firstName:"Steve",
    lastName:"Jobbs",
    number:"617-222-2222",
    address:["15 Idontknow Street", "No Idea", "NO", "33333"]
  }
};

var list = function(friends){
  for (var firstName in friends) {
    console.log(firstName);
  }
}
Ende Neu
  • 15,581
  • 5
  • 57
  • 68
user3472810
  • 435
  • 1
  • 5
  • 13

1 Answers1

3

The property names of your "friends" object are "bill" and "steve". That's what the loop iterates through — the property names. It doesn't matter what variable name you use.

What your loop is currently printing is "bill" and "steve", not "Bill" and "Steve". If you want to log the properties of the objects referenced by the properties of the "friends" object, you have to access those objects. If you wanted the "number" for example:

for (var fn in friends) {
  console.log(friends[fn].number);
}
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Oh you just have me a huge "A-HAH!" moment. I'm beginning to really grasp this stuff and you just helped me so much. THANK YOU!! – user3472810 Aug 05 '14 at 19:40
  • @user3472810 I am very happy for you and I completely understand. Grasping these things is not easy, even if it seems trivial once you "get it". – Pointy Aug 05 '14 at 20:38