We Made A Friend! (works with errors?)


#1

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

search("Jones");

var add = function (firstName, lastName, phoneNumber, email) {
var contact = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
};
contacts[contacts.length] = contact
};

add("Jon", "Smith", "(999) 999-9999", "jsmith@example.com")

list();

OKAY, so I passed the lesson with this code BUT I get this as the result:

Bob Jones
no contact found
Bob Jones
Mary Johnson
Jon Smith

WHY???


#2

Did you expect something else to happen? "WHY" doesn't explain what you want to know!


#3

Sorry, I mean why did it return Bob Jones twice and also a no contact found? Am I misunderstanding what the outcome is supposed to be? I thought the outcome should result in only Bob Jones, Mary Johnson, and Jon Smith (the added contact) being displayed. So, why two of the same name plus a no contact found message? I hope that clarifies better than "WHY?" lol


#4

Get rid of that search("Jones") line. That's why it returns "Bob Jones" twice.


#5

That worked! Thanks for the help!