4/6 Listing Everybody - calling printPerson in for loop question


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

list();

What makes printPerson(i); print out undefined into the console, and printPerson(contacts[i]); work as intended?


#2

@ethanbmnz,
If you call the printPerson(i)
you either are using
printPerson(0); ( the function would try 0.firstName )

and if you call
printPerson( contacts[0] );
you are actually calling the printPerson-function

printPerson( { firstName: "Bob",
               lastName: "Jones",
               phoneNumber: "(650) 777-7777",
               email: "bob.jones@example.com"
               });

#3

'printPerson()' is a function with the parameter 'person'. The variable 'i' refers to the position of an item or object in an array( the contacts array in this case). When you pass 'printPerson()' the argument 'i,' it returns 'undefined' because it expects a 'person ' . Note that 'contacts[i] ' is a person at the 'i' th position on the contacts list.(i.e. contacts array).