Traditional For Loop (for-i)

for (let i = 0; i < array.length; 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];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
  sum = sum + numbers[i];
}
// sum is 60

Same Result as for-of, With the Index Built In

for...of can get you an index too — you just have to track it yourself:

const fruits = ["apple", "banana", "cherry"];
let i = 0;
for (const fruit of fruits) {
  const positioned = i + ": " + fruit;
  i = i + 1;
}

for-i gets the same result, but the counter lives in the loop header instead of lines you
manage by hand:

const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
  const positioned = i + ": " + fruits[i];
}

When to Use For-i

Use for-of when you just need each value. Use for-i when you need:

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