Loop the Loop



Below is my code and the error message I get when I run it. Can anyone please tell me where am I doing wrong ?


We're running a test below to make sure your code works.
TypeError: Cannot read property 'name' of undefined

**// Our Person constructor**
**function Person(name, age) {**
**    this.name = name;**
**    this.age = age;**

**var family = [];**
**// 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);**


Problem is here:

for (var i =0; i <= family.length; i++) {

family is just a normal array. We start indexing array elements from 0. That is why the last element of this array has index family.length - 1.

Let's assume that we have this array:

var names = ["John", "Mike", "Steven"]

Length of this array (names.length) is equal to 3. Index of element "John" is 0, "Mike" -> 1 and "Steven" -> 2.

Your loop will try to access elements at indices 0, 1, ..., family.length - 1, family.length. This last index does not have any value assigned.

You have to change the condition of your for loop to:

i < family.length


i <= family.length - 1


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