Student-friendly HTML, CSS, and JavaScript reference with examples
A traditional for loop gives you both the index (position) and the value.
for (let i = 0; i < array.length; i++) {
// code runs for each index
}
let i = 0 - start counter at 0 i < array.length - continue while i is less than array length i++ - add 1 to i after each iteration const numbers = [10, 20, 30];
for (let i = 0; i < numbers.length; i++) {
console.log(i, numbers[i]);
}
// Prints:
// 0 10
// 1 20
// 2 30
Use for-i when you need:
The variable i IS the index itself:
if (array[i] > i) {
// element is greater than its position
}