Q7 "Search for a friend" - It says I pass but code doesn't work?


#1


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


Although the exercise is passing my code, as soon as I try to search("Bill"), I get no response. It still says I pass, but nothing is printed to the console, when the full contact info should be, so I assume I've done something wrong. Here's my code.


var friends = {};
friends.bill = {
    firstName: "Bill",
    lastName: "Bryson",
    number: "02089945685",
    address: ["321 Fake Street", "London", "England","SE1 1AL"]
}
friends.steve = {
    firstName: "Steve",
    lastName: "Dangerous",
    number: "02079985685",
    address: ["The Backett Building Penthouse", "London", "England","N1 1XX"]
};

var list = function(targetobject){
    for (var x in targetobject){
        console.log(x);
    };
};

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


search("Bill");

console.log("endofcode");

The endofcode bit is just to help me work out what is being produced by the code and what is codecademy testing it.


#2

the function ends the moment a return keyword is reached, so either you need to swap return and console.log:

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

or you should log the returned result to the console:

console.log(search("Bill"));

#3

Oh my god thank you. That makes so much sense. I've been poring over this code for half an hour, finally it works.