Loop the Loop


#1


I'm stuck on this exercise. I don't know how to call the property name in the Array.

When I write the below code, it prints out "TypeError: undefined is not an object (evaluating 'family[i].name')
"
Plz help...


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

// Now we can make an array of people
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);


// loop through our new array
for (var name in family) {
    console.log(family[i].name);
}


#2

a for in loop is for objects. Familiy is a array, use a normal for loop


#3

I wrote the code below and it printed out all the names in the array but again it shows error message.
"TypeError: undefined is not an object (evaluating 'family[i].name')"

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

// Now we can make an array of people
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);


// loop through our new array
for (var i = 0; i<=family.length; i++) {
    console.log(family[i].name);
}

#4

the length of your array is 4, but arrays are zero indexed based (so: 0, 1, 2, and 3) so you need values lesser then (<) family.length, not lesser or equal to (<=)


#5

I got through the exercise but I still did not fully understand. I got it that Arrays start form 0 but I am confused what difference would it make if I set it to <family.length or <=family.length because in every for loop I have written in the previous exercises, I have always set the condition i<=array.length.


#6

in this case, family.length is 4. If you use <=, the values the loop produce are: 0, 1, 2, 3 and 4. But your array doesn't have an index 4. So you shouldn't have 4, so you should use <


#7

Got it. So in every for loop it is preferable to set the condition <array.length instead of <=array.length

Thanks :slight_smile:


#8