27 loop the loop - can't understand difference


#1

i've got two codes for the problem, one works, one doesn't.

as far as i see, there's literally NO DIFFERENCE.

please, help me to understand, what's the difference.

THIS CODE WORKS

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

THIS DOES NOT:

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

// Now we can make an array of people
var family = [];
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);
};

what.
is.
the.
difference?


#2

no, they are not. in the first for loop you use <:

i < 4

in the second you use <=:

 i <= family.length

which means length is 4, so then you get: 0,1,2,3,4 (that is 5, but you only have 4)


#3

aaaa, okay, thanks! it works now (i think the "length" version should work either, but it passed anyway now with the literal 4 :slight_smile: ) thanks.


#4

if you use < in length, it should work fine


#5

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