Hi I have been trying to learn Javascript using codeacademy.com and I have reached an exercise that doesn’t seem to make any sense when why the exercise I have written.This is my code:
(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 printPerson = function(person){
console.log(person.firstName + " " + person.lastName);
}
var list = function(){
var i = contacts.length;
for(var j= 0; j < i ; j++){
printPerson(contacts[i]);
}
};
list();
})();
The problem is in the list function when I try to call the printPerson() function I get that person is undefined but if I write instead of the list() function this:
printPerson(contacts[0]);
printPerson(contacts[1]);
Everything works.What am I doing wrong in the list() function that it doesn’t work?
ihere is a constant. If you replace it:For all arrays
arr,arr[arr.length]will always be undefined. You probably wantcontacts[j].