27/33 Loop the Loop


#1

Hello everyone
This is my code:


function Person(name,age) {
    this.name = name;
    this.age = age;
}
var family = new Array;
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

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

and this is what's the console is printing out(+ the error):


alice
bob
michelle
timmy

We're running a test below to make sure your code works.
alicebobmichelletimmy
TypeError: undefined is not an object (evaluating 'family[i].name')


Can someone tell me what I'm doing wrong?(I'm sorry for my English)


#2
 i <= family.length

The family array has 4 members so length is 4. But the indices just go from 0 to 3 which are 4 numbers (0,1,2,3) but 4 is not included so letting your loop go from 0 to 4 gives you an array member which is not yet defined and which doesn't have a .name property as it is undefined.

I guess you can ignore this output:

alicebobmichelletimmy

that's just a test run for your code.


#3

Thanks, I got it :smile:


#4

You mean leave out the = sgn in i <= family.length; . Please be more specific as it helps relieve the ambiguity caused by the authors. Thanks.


#5

Yes the = in <= is the problem as explained above.