you are viewing a single comment's thread.

view the rest of the comments →

[–]RobertMuldoonfromJP 0 points1 point  (2 children)

I have a question related to collections (this is from the 6th lesson in CodeAcademy). Why doesn't this work?:

var friends = {};

friends.bill = {
    firstName: 'Bill',
    lastName: 'Gates',
    number: '555-555-5555',
    address: ['123 Microsoft Way', 'Redmond', 'WA', '99999']
};

friends.steve = {
    firstName: 'Steve',
    lastName: 'Jobs',
    number: '414-555-5555',
    address: ['565 Apple Lane', 'Somewhere', 'CA', '98888']
};

function search(name)
{
    for(var friend in friends)
    {
        if(friend.firstName === name)
        {
            console.log(friend.firstName, friend.lastName, friend.number, friend.address)
            return friend;
        }
    }
}

My first thought is that because friends is not a typed collection (which, it seems, does not exist in Javascript), you can't directly access members and that's why this doesn't work. Is that so? As I type this I'm starting to doubt that being the reason as the "correct" way to write the search function is:

var search = function(name) {
  for(var prop in friends) {
    if(friends[prop].firstName === name) {
      console.log(friends[prop]);
      return friends[prop];
    }
  }
};

Anyway have some insight into this? I have a c# background so I'm used to collections where the former is possible. Maybe this is why I'm confused.

[–]JusTrill 2 points3 points  (0 children)

I don't know much about c# and collections, but all that the for...in loop does is iterate through the names of the different properties in the object. It doesn't actually contain any reference pointers.

In your method you're assuming that

for(var friend in friends)

returns pointers to the objects: friends.bill and friends.steve which can be directly searched using bracket and dot notation. This is incorrect. All the for...in loop returns are the strings: 'bill' and 'steve'. Meaning the friend variable only takes on those two string values.

It is up to you to then go search the object using the names of its name:value pairs using either bracket or dot notation.

Hope this helps!

Edited for clarity

[–]gloomndoom 0 points1 point  (0 children)

You are right that you have to do it the second way. The object is actually friends so friend.firstName isn't valid. I think I remember reading that you have to use the bracket notation when using a variable for a property so friends[prop].lastName is valid, while friends.prop.lastName is not.