27. Loop the loop error message


#1


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


My code seems fine however i keep getting an error message which is like:

TypeError: Cannot read property 'name' of undefined


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


I even tried copying a gentleman's "correct" code but i got the same message.


#2

Hi @criticalcritics,

If it may help please see the code example below.
Although we can't really testify the reason for the error on the 'gentleman's correct' code without seeing that code I would hazard a guess your error is because you have used a <= in your for loop conditional check.

As the example and comment show, you are essentially getting an index out of range error type, which just means you are going beyond on the upper bound of the index's limit :slight_smile:
You have created a conditional check which will check upto the value 4, however the max value of the Array is only 3.

If you need any further explanation, or would like help with the other code that also gave you an error please feel free to post the exact code snippet and someone will try to help as soon as they can.

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)

console.log(family.length); //length is 4 but family[i] max is only 3

for(var i = 0; i< family.length; i++){ //let's change this from <= to a <
    console.log(family[i].name)
}

#3

thanks a lot, this solved the issue :smiley:
the other person's code had the same error but for some reason he said it worked, i assume he simply rushed his expectations.
thank you


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.