Whys of #4 Listing Everybody


#1


https://www.codecademy.com/courses/building-an-address-book/0/4?curriculum_id=550af85efed2a8c613000001


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) {
    return(person.firstName + " " + person.lastName);
}
var list = function() {
    for (var i = 0; i < contacts.length; i ++) {
        console.log(printPerson(contacts[i]))}
};
list()


So this is what worked, but I am hoping someone can help explain for me what I was originally doing wrong.

  1. I had originally kept in console.log for the printPerson function, as we had done in the previous exercise:
    function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
    Why do we change it?

  2. Originally, I had tried to create the list function as:
    function list() {
    Why do we need to use var function = list here instead?

  3. Then, when I had kept console.log in the printPerson function, I had tried to call it this way:
    for (var i = 0; I < contacts.length; I ++) {
    printPerson(contacts[i]);}
    and when I finished with:
    list()
    it kept telling me I had forgotten to call the function.

Thanks, I really appreciate all help, as I thought I had been understanding up to now and suddenly had lots of problems with this one.


#2

This works, however, there codecademy console oddly prints twice.

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

list();

#3

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