5. Finding that Special Someone (else)


#1

So I am not exactly 'stuck' here but just wondering something.
The output looks like this:

Bob Jones
"Last name wasn't found in your address book."

Why does it also return the 'else' statement?


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) {
            printPerson(contacts[i]);
        } else {
            return "Last name wasn't found in your address book.";
        }
    }
}

search("Jones");


#2

well, now each run/iteration of the loop the if condition see if the person you search for if a match, when this is not the case, else will run

But when have we successfully determined the person we are searching for is not in our address book? When the loop has finished running

so, we only want to return not found after the loop. Get rid of else and place the return after the loop

Doesn't your current code give an error? a return keyword causes a function to end, so your search function ends the moment a person in the address book doesn't match our search query, so even though there are more people in the book, the code never gets there


#3

Nope, no error! But thank you for the explanation! :slight_smile:


#4

Graag gedaan (You're welcome), everything clear?


#5

Haha tof! Nederlander? Yeah I got it ! :slight_smile:


#6

ja, er zijn nederlanders op dit forum :wink: Good to hear :slight_smile:


#7

Had niet anders verwacht, toch altijd even verrast wanneer je er eentje tegenkomt!


#8

klopt, maar daarom is het wel een leuke verassing als je ze tegen komt :slight_smile:


#9

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