6/6. What's wrong with my code?


#1

Can't find bug in "add" function...

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];
var contactsLength = contacts.length;
function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}

function list() {
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}

/*Create a search function
then call it passing "Jones"*/
var search = function(lastName) {
for (var i = 0; i < contactsLength; i++) {
if (lastName === contacts[i].lastName) {
printPerson(contacts[i]);
}
}
};

var add = function (firstName, lastName, phoneNumber, email) {
contacts[contacts.length] = {
firstName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
}
};
add("Jack", "Meck", "223-322", "email.com");
list();


#2

@herzogru,

The problem is in your list =function=

function list() {
   var contactsLength = contacts.length;
   for (var i = 0; i < contactsLength; i++) {
         printPerson(contacts[i]);
   }
}

#3

Thank you! Of course you mean //var contactsLength = contacts.length;
Can I ask you about SCOPE which is m entioned in Instructions? I understood it like I can write it out of 'list' and 'search' functions
/*var contacts = [bob, mary];
var contactsLength = contacts.length;
function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}

function list() {
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}*/
and it works good in 5/6, why it's wrong in 6/6?


#4

You extended the contacts-Array with 1 Element,
but the global-variable contactsLength is not updated,
and thus the list =function= as presented in your Original Post
would only list the 2 Elements....