4.listing everybody


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

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

list();

its said the code is ok and i can continiue to next lesson but, i skipped on instruction number2 and it prints out the whole information about bob and marry twice the qeustion is what i need to do on instruction number 2 coz i dont understand it and why does it print twice, or does it even matter? thanks for help


#2

It prints twice because notice this line

for(var i = 0; i < contacts.length; i++) {

It repeats it 2 times since contact.length is 2. Because there are two contacts. If you wish to do it one time you can just change the contacts.length to <=1 ...


#3

but its ok this way?


#4

Hi try to remove the call function list();


#5

That would not call the function. So it would give @psynnet an empty result/set...


#6

I don't know about number two, but the reason it's printing out the information twice is because you're telling it to.

printPerson(contacts[i]);

Is all you need. The printPerson function automatically console logs.

console.log(contacts[i])

Just tells it to do it again without calling printPerson.


#7

I went back and checked. For instruction 2 you just need

var contactsLength = contacts.length;

I don't know why yet, I haven't gotten far enough to use it.


#9

I've also did the same and got double the log.

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;
    console.log(contactsLength);
    for(var i = 0; i < contactsLength; i++){
        printPerson(contacts[i]);
    }
}
// list();

It seems like commenting list() only output the result once...
I'm not sure if this exercise already has a list() prepared for us or not.