For-Of Loop Basics

for (const item of array) { }

A for-of loop goes through each element in an array, one by one.

for (const item of array) {
  // code runs for each item
}

How It Works

The variable (item) gets each value from the array:

const numbers = [10, 20, 30];
const doubled = [];
for (const num of numbers) {
  doubled.push(num * 2);
}
// doubled is [20, 40, 60]

Works on Strings Too

A string is just a list of characters, so for...of walks through it one character at a
time:

const letters = [];
for (const letter of "cat") {
  letters.push(letter);
}
// letters is ["c", "a", "t"]

Key Points

  • Use const for the loop variable (it changes each iteration)
  • The loop runs once for each element (or character)
  • You get the value directly, not the index