JavaScript
This page explains the three parts of a JavaScript for loop: initialization, condition, and update.
Goal: read and write a fixed-count loop safely, while knowing what each part controls.
for loops
A for loop is useful when a block should repeat a known number of times or while a counter moves through a range.
JavaScript
for (let i = 0; i < 5; i += 1) {
console.log(`Iteration ${i + 1}`);
}- Initialization
let i = 0runs once before the first check.- Condition
i < 5is checked before each iteration. When it becomes false, the loop ends.- Update
i += 1runs after the body and moves the loop toward its end.
Process an array by index
JavaScript
const fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i += 1) {
console.log(fruits[i]);
}The condition uses fruits.length, so the loop stops before the index goes past the last element.
Keep the loop safe
- Make sure the update changes the value used by the condition.
- Use
breakwhen a search can stop early, andcontinuewhen one item should be skipped. - Use
whilewhen the number of iterations is not known in advance and the condition is the main idea. - For arrays,
for...of,filter(), ormap()may express the intent more clearly than an index loop.