What is a loop?
Computers are great at repeating tasks. A loop is a control structure that runs a block of code over and over until a condition is no longer true.
A for loop puts three pieces of information on one line: where to start, when to stop, and how to update the variable each time.
Simple definition: A for loop repeats code while counting from a start value to an end value.
Try it: Loop Visualizer
Below is the same kind of tool that powers the CodeHS For Loop Visualizer PowerUp. Type a start and end value, then press Step to see each part of the loop run, or Run to animate it.
console.log(i);
}
Parts of a for loop
Every for loop has three parts separated by semicolons:
- Initialization:
let i = 0creates the loop variable and sets its starting value. - Condition:
i < 10is checked before each repetition. If it is true, the loop body runs. - Update:
i++adds one to the variable after the body runs.
The loop keeps going as long as the condition is true. As soon as i reaches the maximum value, the loop stops and the program continues with the code after the loop.
Common loop mistakes
- Off-by-one errors: The condition
i < 10runs 10 times (0 through 9), not 11. Using<=changes the count. - Infinite loops: If the update step is missing, the condition may stay true forever.
- Wrong start value: Starting at 1 instead of 0 can skip the first element in a list or produce one fewer iteration.
Quick quiz
1. What does the update part i++ do?
2. How many times will for (let i = 0; i < 5; i++) run?
3. In the visualizer, what happens after the console prints the value of i?
Keep exploring programming
Loops are everywhere in code. Next, you can learn about lists, while loops, or how to use loops to draw patterns and process data.
Part of the Programming Concepts tutorial series.