7: search for a friend (question on why it works)


#1


https://www.codecademy.com/courses/javascript-beginner-en-3bmfN/0/7?curriculum_id=506324b3a7dffd00020bf661#

This code works, but I don't understand why. Specifically, what does "name" refer to? I know it's the function argument, but when the if statement runs, what is friends[key].firstName comparing itself to? Why does it === name? What is name? If this makes no sense, let me know and I'll try to explain better. Thank you!

if(friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}


var friends = {
    bill: {
firstName: "Bill",
lastName: "Gates",
number: "555-555-1212",
address: ['One Microsoft Way','Redmond','WA' ,'98052']
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "555-555-1213",
address: ['1 Infinity Loop','Cupertino','CA' ,'12345']
}
};

var list = function (friends) {
for (var i in friends) {
console.log(i)
}
}

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


#2

As you said, name is the argument to the function.

Are you asking where the argument is coming from? The argument is provided by the caller.


#3

Im going to respond to your questions.. first:

Well as you can see its the function argument, you should have learned that before taking on this exercice

Ok so basically friends[key] is like itterating thourgh an obejct.. so the key gets replaced by the index. Gates bieng 0 and Jobs bieng 1. then you use dot notation operator to gets its child key/value pair.. in this case bill and steves first name... so then it compares it with the name you passed in as arguments.. basically this code:

Translates to

if(steve.firstName == name){

and

if(gates.firstName == name)

And then final question:

That is strict equality operator.. i explained it in great detail here: