7. Search for a friend - Its hard to understand


#1

Hello everyone. I find it difficult to understand how does this code work exactly. Could you please help me figure it out?

First, why do we use for(var firstName in friends) ? Is there any other way to create a loop that it will check this as many times as the firstname exists? (Just wondering). Now for the main difficulty, why do we have to specify the function the firstName is? Can we do it with any other way and if so how do i know which is right to use at each time.

if(friends[firstName].firstName === name)


var friends = new Object();
friends.steve = 
{
    firstName: "Steve",
    lastName: "Smith",
    number: "666-666-666",
    address: []
};
friends.bill = 
{
    firstName: "Bill",
    lastName: "Smith",
    number: "666-666-666",
    address: []
};
var list = function (friends) 
{
    for(var firstName in friends)
    {
        console.log(firstName);
    }        
}
var search = function (name)
{
    for(var firstName in friends)
    {
        if(friends[firstName].firstName === name)
        {
            console.log(friends[firstName]);
            return friends[firstName];
        }
    }     
}


#2

here:

for(var firstName in friends)

why did you choice firstName as iterator? The for in loop will loop over friends, containing the properties (bill and steve, not to confuse with Bill and Steve) of friends. So using something like prop would make more sense.

so prop will contain bill and steve:

for (var prop  in friends){
   console.log(prop);
}

so now we can use prop as key to get the values from bill and steve:

for (var prop  in friends){
   console.log(friends[prop]);
}

then we can use .firstName as property to the firstName value from bill and steve

for (var prop  in friends){
   console.log(friends[prop].firstName);
}

#3

friends is an object, with two properties: bill and steve

bill and steve and are also objects (and properties of friends)

bill and steve have a number of properties (firstName, lastName), and this properties have values.

what is making it confusing is this:

[prop]

normally you would do:

friends.bill.firstName

but because prop contains a string (thanks to the for in loop), js forces you to use associative array notation instead:

friends[prop].firstName

6. List 'em all!
#4

Okay, i got it about the properties and the objects. So friends[prop] is just another way to access the property's value when the value is a string?


#5

yes, you could also do:

friends["bill"]

#6

Uh-huh! Thank you , your answers gave me a better idea of how this works.


#7

in a for loop we can't use:

friends.prop

because prop contains a string. and .propertyName only work for property names, not string property names (if that make sense, hope so)


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.