5. Finding that Special Someone


#1

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

This is what I'm getting in the console:
Bob Jones
No person found

Not sure why the "else" in my "if/else" statement is printing to the console. Is the loop running through the entire "if/else" statement before logging in Bob Jones? Do I need an else statement? I saw other codes with coders excluding the "else" statement and they stated the program worked for them. But I thought you have to include an "else" in an "if/else" statement? Is there an exception to this rule?

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) {
    for(var i=0; i<contacts.length; i++) {
        if(lastName === contacts[i].lastName) {
            printPerson(contacts[i]);
        } else {
            console.log("No person found");
        };
    };
};
    
search("Jones");

#2

No exception, because it's not a rule

You always print either the person or not found, so for each person that doesn't match, it'll print not found.


#4

Oh ok. Thanks for clarifying!


#5

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