7. Search for Friend


#1

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

For some reason, the search function doesn't return contact information for Steve.


var friends = {};
friends.bill = {
    firstName: 'Bill',
    lastName: 'Madison',
    number: "123-456-7890",
    address: ['9182 Williams Rd', 'San Antonio', 'TX', '78291']
};
friends.steve = {
    firstName: 'Steve',
    lastName: 'Hungry',
    number: "908-745-4123",
    address: ['4810 Langley Drive', 'Alto Palo', 'CA', '91820']
};

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

var search = function(name) {
    for (var key in friends) {
        if (friends[key].firstName === name) {
            console.log("First Name: " + friends[key].firstName);
            console.log("Last Name: " + friends[key].lastName);
            console.log("number: " + friends[key].number);
            console.log("address: " + friends[key].address);
            return friends[key];
        } else {
            return "No one is in the address book."
        }
    }
};

var sch = prompt("Who are you searching for?")
search(sch);


#2

a function ends the moment a return keyword is reached.

so you loop over friends, and then first you get bill:

Bill === Steve

which is false, so return "No one is in the address book." is executed, causing the function to end.

Place return no one is found after the for loop


#3

Brilliant! Didn't catch how the else statement would be affected by the for/in loop. Thank you Stetim


#4