6. We Made a Friend!


#1

Hey, I've look at this code way to long, but I can't figure out what the problem is. When I run the code I get the error "Oops, try again. It looks like there are still only two items in the contacts array."

Thankful for 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]);
	}
}

function search(lastName) {
    var contactsLength = contacts.length;
    for (var i = 0; i < contactsLength; i++) {
        if(contacts[i].lastName === lastName) {
            printPerson(contacts[i]);
        }
        else {
            console.log("Contact not found");
        }
    }
};

search("Jones");

function add(firstName, LastName, phoneNumber, email) {
    contacts[contacts.length] = {
        firstName: firstName,
        lastName: lastName,
        phoneNumber: phoneNumber,
        email: email
    }
};
    
add("Peter", "Parker", "(650) 999-9999", "spider.man@example.com");
list();

#2

HI as argument in your add function

function add(firstName, LastName, phoneNumber, email)

you wrote LastName instead of lastName


#3

Wow, I thought I checked all typos >.<
Thanks, that solved it!


#4

Typos are really painful


#5

I have an interesting question for you... unfortunately I don't have an answer. Maybe you do or someone else does.

I see what you are trying to do with your else statement. However, I believe there is a problem with it. Overtime your loop runs, which will be once less times than the amount of contacts that you have. If your search doesn't find the person's last name it will actually print out "Contact not found". This doesn't seem like much of a problem until you consider if you had 1,000,000 names in your contact list, and you searched for the last name "Jones" if there was only one person with the last name Jones, your console would print out "Contact not found" 999,999 times and somewhere in there it would print out "Jones" once.

I think when you put it in there, you had the intentions that if all the loops where completed and no last name was found it would then print out once "Contact not found".
Was that your intention?

I may be completely wrong here.


#6

"everytime" replace the word "overtime"