For this lesson it says that ‘’ Our condition for this loop is 'i < arr.length, which stops the loop when i is equal to length ‘’ .
But
shouldn’t it be “which stops the loop when ‘i’ is ONE less than length”?
If the condition met the array length, then there would be no number after the last iteration of the loop because arrays have zero based indexing?.
Challenge: Iterate Through an Array with a For Loop
var myArr = [ 2, 3, 4, 5, 6];
for (let i = 0; i < myArr.length; i++) {
console.log(i)
}
You will notice this is printed to the console:
0
1
2
3
4
Now, if the loop stopped, when i is one less than myArr.length, then 4 would not have been printed to the console.
In order for 4 to be printed, i needs to be equal to 4 (one less than myArr.length), then this line is run again:
for (let i = 0; i < myArr.length; i++) {
Now, i is still < myArr.length… So, the loop can run. However, when i === 5 (i === myArr.length), then the loop stops. Not before (one less than length).
That came out a lot more muddled than it is in my head, but I hope it is somewhat clear.