3. Displaying People - Want to see if this is a viable alternative


#1

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

Oops, try again. Did you create a function called printPerson?

My code below produces the output that the prompt is asking for, but I wanted to see if this was a viable alternative solution, or is my logic off? Looking at other forum posts, it looks like the way that the prompt would like the answer is:

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

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

But is the way I did this below correct as well?

Thanks in advance.


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

console.log(contacts[person].firstName + " " + contacts[person].lastName);
Why're you passing person to contacts Array ?

person is some name (variable)..suppose mary.(As it's an Object)

to find marry's firstname I can use dot notation like this...

mary.firstName


#3

Understood. Just so I'm crystal clear on it, it technically works in this example to pass whatever "person" to contacts array like contacts[bob].firstName, but best practice is to use variable.object notation and then when you call function you specify what you'd like to call as in printPerson(contacts[0]);?

Thx


#4

@adopp
But is the way I did this below correct as well?

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

No as Your Array needed index but you're passing variable (which is an Object) which will not work.
You need to loop over length of Array contacts and pass index to it.


#5

Perfect! Thank you for taking the time to clarify for me.


#6

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