Contact List


#1


I am driving myself insane trying to work out what's happening on the search function on the contact list.


No matter what argument I pass to the search function, it gives me Bill (I've run it through JS Bin, same thing). Even if the argument is not one of the keys, for instance Dave or Mike, I still get Bill. Somewhere, the code is completely ignoring my if statement and jumping straight to printing the key.

Oddly, if I remove the return command, I get the contact info for all three, regardless of what I search


var friends = {
    bill: {
        firstName: "Bill",
        lastName: "Gates",
        number: "1",
        address: ['1 Moneyland Heights', 'Moneyland', 'MunA', '123456']
    },
    steve: {
        firstName: "Steve",
        lastName: "Jobs",
        number: "666",
        address: ['2 Moneyland Heights', 'Moneyland', 'MunA', '123456']
    },
    gavin: {
        firstName: "Gavin",
        lastName: "Free",
        number: "42",
        address: ['3 Moneyland Heights', 'Moneyland', 'MunA', '123456']
    }    
};
var list = function(friends) {
    for(var key in friends) {
        console.log(key);
    }
};
var search = function(name) {
    for (var key in friends) {
    if(name === friends[key].firstName);
        console.log(friends[key]);
        return friends[key];
        
    }
};


7. Search for a friend
#2

normal if condition:

if (condition){
   // do something if condition is true
}

in your case, you have a unnecessary semi-colon and the curly brackets are missing

what this means is that the if statement get interrupted and the code on the lines below get executed:

         console.log(friends[key]);
        return friends[key];

which means the first result is returned (given a function ends the moment a return keyword is reached), when you remove the return keyword, everyone will be logged

your if statement was rendered useless. Hope this helps


#3

Well now I feel dumb =D Completely forgot to contain the conditional actions in the brackets.

Need to go back quite a few lessons I think.

Many thanks for the help!


#4

you're welcome :slight_smile:


#5