Finding that Special Someone


#1

I wrote the below code and got through the exercise. It prints out the Person's name if it's last name matches with the last name i searched for.

It prints out the following:

Bob Jones
undefined
"not available"

I don't understand why is it printing out "not available"?

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(contacts[i].lastName === lastName) {
		    console.log(printPerson(contacts[i]));
		} else {
		    return "not available";
	}
   
 }

}
search("Jones")

#2

printPerson() already logs. What this will log is, undefined.

If I'm not mistaken, all you need to log is contacts[i], and then return it. There should not be an else branch.


#3

Sorry I did not understand. What will the console print out if I search for a last name that is not there?


#4

It should not print out anything. For this exercise you are searching for something that you know is there; and, the instructions do not ask us to check for or log 'not found'.


#6

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