How do you write a for loop in JavaScript?
A for loop packs the three loop ingredients — initialise, condition, update — into one compact header, making counting loops tidy.
The for loop is the go-to for counting a known number of times. Its header has three parts separated by semicolons: an initialisation, a condition checked before each pass, and an update run after each pass.
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
The general shape:
for (initialization; condition; update) {
// code to repeat
}
It does exactly what an equivalent while loop does, just with everything gathered in one line instead of scattered around:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Its most common use is walking an array by index, where .length supplies the stopping point:
let fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Keeping the three parts together in the header makes counting loops less error-prone — there's no separate update line to forget, which is a frequent cause of infinite loops in while.