Documentation

Student-friendly HTML, CSS, and JavaScript reference with examples

Sections

Traditional For Loop (for-i)

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
}

Three Parts

  1. let i = 0 - start counter at 0
  2. i < array.length - continue while i is less than array length
  3. i++ - add 1 to i after each iteration

Accessing Elements by Index

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

When to Use For-i

Use for-i when you need:

  • The index (position)
  • To compare value with its position
  • To access elements by index

The Index Variable

The variable i IS the index itself:

if (array[i] > i) {
  // element is greater than its position
}