Loop the loop


#1

Hey guys! Why does my code print just undefined 4x instead of the names of the family??

function Person (name, age) {
this.name = name;
this.age = age;
}

family = new Array();
person1 = new Person ("alice", 40);
person2 = new Person ("bob", 42);
person3 = new Person ("michelle", 8);
person4 = new Person ("timmy", 6)

for (i=0; i<4; i++) {
console.log(family[i])
}


#2

You never added the people to family. Therefore all the elements are undefined.


#3

Could you pls show me how to do that.? I'm confused.. :slightly_smiling:


#4

You could wait to initialize family and do:

var family = [person1, person2, person3, person4];

Or you could add them after it's initialized:

family.push(person1);
family.push(person2);
//For each person

#5

I got it! Thanks for your help :ok_hand:


#6

You're welcome! :slightly_smiling: