27 Loop the Loop


#1


https://www.codecademy.com/courses/spencer-sandbox/4/2?curriculum_id=506324b3a7dffd00020bf661#


So I'm getting the TypeError, 'family[i] is undefined'. However, this code looks exactly like those that have been working here. Any ideas? Thanks!


function Person(name,age){
this.name=name;
this.age=age;
};
var family=new Array();
// Now we can make an array of people
family[0]=new Person("alice",40);
family[1]=new Person("bob",42);
family[2]=new Person("michelle",8);
family[3]=new Person("timmy",6);
// loop through our new array
for(var i=0; i <= family.length; i++){
    console.log(family[i].name);
};


#2

Hi just remove tthe <= and put just <


#3

Oh, Thank you!

Can you please explain why it would throw that error?


#4

Hello @wizmarco, because when you make it <= family.lenght which is 4, the loop would try to iterate 5 times as we give i an initial value of 0. Our array however has 4 elements and when i = 4 and the loop tries to call family[4] it gives this error as the array does not have any element in that slot.