for Loops
Prerequisites: Loops
A for...of loop runs its block once for every item in an array or
string — the modern, idiomatic way to loop over a sequence of values.
Syntax
for (const item of sequence) {
// ...
}
Example
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
Expected output
apple
banana
cherry
The classic C-style loop (for (let i = 0; i < n; i++)) still works
and is useful when you need the index itself, but for...of is
preferred when you just need each value.
Practice
Log each number from 1 to 5 (inclusive) using a for loop.
Show solution
for (let i = 1; i <= 5; i++) {
console.log(i);
}