5/6 Finding That Special Someone, Jones Found, Johnson not Found


#1

Hi using the following code I can search for and find Jones but not Johnson. The code is accepted as a solution.

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

function list() {
    var contactsLength = contacts.length;
    for (var i = 0; i < contactsLength; i++) {
        printPerson(contacts[i]);
    }
}

/*Create a search function
then call it passing "Jones"*/
function search(lastName) {
    var contactsLength = contacts.length;
    for (var i = 0; i < contactsLength; i++) {
        if (lastName === contacts[i].lastName) {
            return printPerson(contacts[i]);
        } else {
            return "Contact not found";
        }
    };
}

search("Johnson")

Using Johnson as a search parameter I get "Contact not found".
I cant think of why it wont work for the second contact.


#2

@bashiros,

You will have to remove

else {
        return "Contact not found";
    }

from your search function,
because a return statement will EXIT the FOR-loop and therefore the search function.