var arr = [10,9,8,7,6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
arr.length in this case would be 4 right? if so then the code should stop executing at 3 which would be number 7 but it logs the entire array. What am I missing?
let me try to explain what is happening in this code of yours below:
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
arr.length would give you 5. however, array indexes start from 0.
Since we want the iteration to go from 0 to 4 (i.e the indexes of our array), we have to say that i < arr.length.
if we say that i <= arr.length, the loop would go from 0 to 5. At the fifth element, it would return undefined because there is no arr[5].
so, the code would print something like this: