var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Sorry this explanation of the example got me totally lost:
Remember that arrays have zero-based indexing, - Okay, I get that.
which means the last index of the array is length - 1 . - that I don’t get.
Our condition for this loop is i < arr.length (= 4) which stops the loop when i is equal to length (why? it says <, not equal to) .
In this case the last iteration is i === 4 (4 because it’s less than the length of 5?) i.e. when i becomes equal (again why = when it says <) to arr.length and outputs 6 to the console.
Why would the outcome not be 7, since the loop says < not equal to.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
Please use the “preformatted text” tool in the editor (</>) to add backticks around text.
Okay. Let’s look at an array here, where the value of each item is the index:
[0, 1, 2, 3, 4].
This is an array of length 5. The last item in the array has an index of 4 (because arrays have zero-based indexing), so 4 is the last value you want i to reach. If you try to access index 5 of this array, you’ll get undefined.
In a for loop, your condition i < arr.length tells the code when to run the loop, not when to stop.
So the loop will only run while i is smaller than arr.length. If your condition was i = arr.length, the loop would only run while i = 5.
console.log() tells your code to print whatever is between the parentheses to the console. For the FCC built in editor, the console is the small window below your code.
Using console.log() helps you see what your code is doing at any step - I use it all the time when I am writing code or debugging code that is already written.