4. Listing Everybody TypeError: Cannot read property '0' of undefined


#1


help >_< with this error message:
TypeError: Cannot read property '0' of undefined


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++) {
    console.log(printPerson.contacts[i]);
    }
};

console.log(list(contacts));


#2

this line:

console.log(printPerson.contacts[i]);

printPerson is a function call. write it as such


#4

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

I removed the console, still TypeError: Cannot read property '0' of undefined
Thank you so much kindly!:blush:


#5

that is not what i said, i said printPerson() is a function call, so you need to use functionname + () to call a function.

At this point in the course, i assumed you know what a function call is


#6

I have no idea, please teach me :cry:
I am sorry I cheated from other posts and found these code:

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

list();

Maybe list() is to call the function?
The TypeError: Cannot read property '0' of undefined still is there. help ><


#7

look, you have a function called printPerson:

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

so then here:

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

you should call the printPerson function:

for (var i = 0; i < contactsLength; i++) {
    printPerson(argument)
    }

see how i call the printPerson function passing an argument, now you can guess what the argument is. What you did (the . notation) is used to access properties of objects. printPerson is not an object


#8

I see! The argument is bob and mary, which is why we use the for loop to call both of them. The printPerson + () is used to call the function passing those arrays. You're so smart! Thank you!! :laughing:


#9