Loop the Loop right but wrong way


#1

Hello everyone. i have saw everyone comments on Loop the Loop but can’t get any answer but when i remove “.name” from in for loop console log it all names and age at the same time it correct my programe also give an error of undefined i want perfect code but can’t understand please help here is my programe code.

// 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]);
}

the answer he gives is here

{ name: ‘alice’, age: 40 }
{ name: ‘bob’, age: 42 }
{ name: ‘michelle’, age: 8 }
{ name: ‘timmy’, age: 6 }
undefined


We’re running a test below to make sure your code works.
{ name: ‘alice’, age: 40 }{ name: ‘bob’, age: 42 }{ name: ‘michelle’, age: 8 }{ name: ‘timmy’, age: 6 }undefined

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

it gives my answer but it can’t correct my programe and show error
"TypeError: family[i] is undefined"


#2

the problem is here:

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

using lesser then or equal to (<=) operator causes problems, but why? because the length is 4, but arrays are zero indexed based, so the highest index of the array 3

currently because you use <= the loop also attempts to access index 4 (which doesn’t exist), this shouldn’t happen

change the operator so 4 is not included


#3

Thanks i get it right anser thank you so much


#4