3.8 for Loops and Array Traversal
A loop repeats a block of code. The while loop in the previous section repeats while a condition stays true. A for loop is better when you can describe the repetition with a counter: start here, continue until there, update each time.
The lab below adds 1 through 5. Step through it and watch i and sum change.
The three parts of a for loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}The parentheses contain three parts separated by semicolons:
1. Initialization let i = 1: runs once before the loop starts. 2. Continue condition i <= 5: checked before each iteration. 3. Update i++: runs after each iteration.
The flow is:
initialize -> check -> run body -> update -> check -> ...When the condition becomes false, the loop stops.
Fixed-count repetition
Use a counting loop when the number of repetitions is known:
for (let i = 0; i < 3; i++) {
console.log("Practice JavaScript");
}This prints the same message three times. Notice the common zero-based pattern:
for (let i = 0; i < count; i++) {
// runs count times
}Accumulation
Loops often build a result step by step:
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(sum); // 5050sum is an accumulator. It starts at 0, then each iteration adds one more value.
A moving-window example
Some loops do not just count upward. They keep a small "window" of previous values and slide it forward. Fibonacci numbers are a classic example: each new term is the sum of the previous two.
Looping through an array by index
Arrays use zero-based indexes, so a classic loop looks like this:
const scores = [88, 92, 75, 100];
for (let i = 0; i < scores.length; i++) {
console.log(`Student ${i + 1}: ${scores[i]}`);
}The last valid index is scores.length - 1, so the condition is i < scores.length, not i <= scores.length.
for-of: process each item directly
When you do not need the index, for...of is simpler:
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}Use an index loop when you need positions. Use for...of when you only need the values.