Finding that Special Someone


#1


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


Please help. My code below is printing both " Bob Jones" and "0 match" on the console.

I don't know why.


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(i=0; i<contactsLength; i++){
        if(contacts[i].lastName === lastName){
            printPerson(contacts[i]);
        }else{
            console.log("0 match");
        }
    }
};

search("Jones");


#2

because for bob if is false, so else will run. The whole for loop should run first, you can find an example with explanations here on how to change this


#3

Loop starts

Is the lastName of contacts[0] === "Jones"? Yes: Call printPerson()
Is the lastName of contacts[1] === "Jones"? No: Log "0 match"

Loop ends

Read the example stetim94 shared.


#4

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