27/33 - Loop the loop


#1

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 x = 0; x <= family.length; x++) {
console.log(family[x].name);
}

Above is my code and when executed i got a message error that says "TypeError: Cannot read property 'name' of undefined". I dont know why i got it. Can someone plz explain that to me? Thanks a lot


#2

Hi @antonritter,

Please see the code sample below. Keep in mind that array indexing starts at 0 and you had a <= in you for loop... this should get you going. The problem was that you were trying to call an index that did not exist.

       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 x = 0; x < family.length; x++) { //because of array indexing only use a < than here not <=
           console.log(family[x].name);
        }

#3

Oh i see :grinning: Thank you so much, Mike !!!!


#4

Also thanks for help :smiley: