JavaScript For Loop
A for loop repeats a block of code a controlled number of times, making it ideal for counting and walking through collections.
The anatomy of a for loop
The classic for loop packs three parts into its header, separated by semicolons: an initializer that sets up a counter, a condition checked before every pass, and an update that runs after each pass. Together they give you precise control over how many times the body runs.
Counting from 0 to 4
<!DOCTYPE html>
<html>
<body>
<h2>Counting from 0 to 4</h2>
<script>
for (let i = 0; i < 5; i++) {
console.log("Iteration", i);
}
// Iteration 0
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4
</script>
</body>
</html>- Initializer (let i = 0) runs once before the loop starts.
- Condition (i < 5) is tested before each pass; the loop ends when it becomes false.
- Update (i++) runs after each pass, usually to move the counter forward.
- The body runs only while the condition holds true.
Looping over arrays
One of the most common uses of a for loop is visiting each element of an array by its index. The array's length property tells the loop when to stop, so the same code works no matter how many items the array holds.
Reading every item in an array
<!DOCTYPE html>
<html>
<body>
<h2>Reading every item in an array</h2>
<script>
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(i, colors[i]);
}
// 0 red
// 1 green
// 2 blue
</script>
</body>
</html>Note: When you only need the values and not the index, the modern for...of loop is cleaner: for (const color of colors) { console.log(color); }. Reach for the indexed for loop when you need the position or want to skip or step through elements.
Choosing the right for variant
Note: Avoid changing the array's length while looping over it by index, and be careful that your condition can actually become false. A loop whose condition never turns false becomes an infinite loop and freezes the program.