Question in 'Loop the Loop'


#1

Why does this pass...

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

but this doesn't?

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

The only difference is < instead of <=, which I thought would work the same? Is it because we are referencing an array of objects and not a number?

These are the small things I question about this language at times. In one situation < would exclude the last number or object where as <= would include it.

Hopefully this makes sense.


#2

i try to explain

var numbers = [1, 2, 3, 4, 5];
console.log(numbers.length);

result is 5

But the index from an array begins with 0 to get five values you count to 4 not to 5

values from array 1,2,3,4,5
index from array 0,1,2,3,4

i <= numbers.length

Your loop runs from 0 to 5 and you should get an out of index error or something like that.
Or can you tell what the six value is :slight_smile:


#3

an array in JavaScript is a ZeroBase object. this means if you have an array with 4 cell your array cell index is:

| x | y | z | a |
| 0 | 1 | 2 | 3 |

index 4 is not exist.

when you get length of this array will return to you 4. and
family[4].name is not exist and you get error.

for solve this we use < instead of <=, until my counter go to 3 and in value 4 will not run this loop.


#4

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