Iterate Through an Array with a For Loop - further explanation [SOLVED]

Iterate Through an Array with a For Loop - further explanation [SOLVED]
0.0 0

#1

Tell us what’s happening:

In the explanation the following code was used.

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?


#2

Try:

console.log(arr.length)

and see what you get :slight_smile:


#3

Run your code through this visualizer, I know it helps me like crazy understand what’s going on

http://www.pythontutor.com/visualize.html

you can change the written code to JavaScript ES6 and then click visualize execution. It steps through the code like a debugger,

don’t forget the console.log statment @oliverdudman put in there


#4

When we count indices, we start counting at 0. So the last index is 4

But when we count the length, we start at 1. So the count is 5

Which is why to stop at the last index we use array.length - 1

It’s not your fault. Just javascript quirks.


#5

arr.length should return 5. if i am seeing properly, the indexes for the arrays should return the following:

console.log(arr[0]) ; //should return 10
console.log(arr[1]) ;//should return  9
console.log(arr[2] );//should return  8
console.log(arr[3] );//should return 7
console.log(arr[4]); //should return  6

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]);
}
  1. arr.length would give you 5. however, array indexes start from 0.
  2. 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.
  3. 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:
10
9
8
7
6
undefined

Hope this makes sense :blush: