Displaying People


#1

https://www.codecademy.com/courses/building-an-address-book/0/3?curriculum_id=506324b3a7dffd00020bf661#

Did you create a function called printPerson?

I have no idea why this error is happening. I am printing out the full names of both people like I should. Can someone explain why I am failing this exercise?



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];

// printPerson added here

var printPerson = function(person) {
    console.log(contacts[person].firstName + " " + contacts[person].lastName);
};

printPerson(0);
printPerson(1);



#2

By hardcoding the array name in the function you take away all purposeful, meaning portable and re-usable, value. Dedicated code makes for very private functions. It is not wrong as such, just wasteful. Better to make a function that is not dedicated to any global objects. One that takes an object and does something with it. Any object.

printPerson(contacts[0])
printPerson(contacts[1])

The above calls pass the array element reference to the function. This will be person objects.

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

Notice that now the function is completely shareable with any object that has a firstName and a lastName property. It can be a direct call or an element in any array. We declare it in the call expression, not the function.


#3

Thanks for the help. I now see why that would not be a good way to do code like that.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.