5. Finding that Special Someone


#1

https://www.codecademy.com/courses/building-an-address-book/0/5?curriculum_id=506324b3a7dffd00020bf661#

Hi everyone !

My code works I got the "Way to go message", it prints out "Bob Jones" to the console but it also prints the else statement which is "Sorry, this person isn't in the list".

Can anyone tell me why please.

Thanks for your help

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"*/

var search = function(lastName){
    var contactsLength = contacts.length;
    for(var i = 0; i < contactsLength; i++){
        if (lastName === contacts[i].lastName){
            printPerson(contacts[i])
        }else{
            console.log ("Sorry, this person isn't in the list");
        };
    };
}

search("Jones");

#2

You are missing a semicolon:

printPerson(contacts[i])


#3

Hi megaplayer47736 !

Thank you very much for your answer but it actually doesn't change anything.

I still get the else statement printed on the console.


#5

It is printing the "else" statement because it is inside the "for" loop, which loops through all of the elements in your array. So for each element in the array, it is printing either the name (when it is a match) or your "sorry" message (when it is not a match).

If you want to display a message when the name is not found in the array, then you should do so after the for loop has completed. One way to do this would be to set a boolean variable to "true" when a match is found, then check the value of that variable after the loop is over. If it is false, then display your "sorry" message.


#6

Great !
Thank you so much for your explanations and for your time !
Now that you told me that it looks obvious :wink:

Thanks again !


#7

No problem! I didn't catch it at first, either. :wink:


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.