Loops in JavaScript
Loops in JavaScript
~12 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026
To process several transactions, our budget app needs loops. This chapter covers all four loop forms JavaScript has – arrays themselves follow in chapter 10, for now we work with simple numeric ranges.
The classic for loop
for (let month = 1; month <= 12; month++) {
console.log(`Month ${month}`);
}
// Prints 'Month 1' through 'Month 12'The three parts in parentheses: initialization (let month = 1, runs once before the loop), condition (month <= 12, checked before EVERY iteration), update (month++, run after EVERY iteration).
while: as long as a condition holds
let balance = 1500;
let month = 0;
while (balance > 0 && month < 24) {
balance -= 200; // monthly fixed costs
month++;
}
console.log(`Lasts for ${month} months.`);do...while: at least one run guaranteed
The difference from while: with do...while, the loop body runs FIRST, and the condition is only checked AFTERWARD – so the body is guaranteed to run at least once, even if the condition is false from the start.
let attempt = 0;
do {
attempt++;
console.log(`Attempt ${attempt}`);
} while (attempt < 3);
// Prints 'Attempt 1', 'Attempt 2', 'Attempt 3'for...of and for...in: a preview
Two more loop forms are made specifically for ITERABLE values – we'll get to know arrays and objects in detail only in chapters 10-12, here's a quick preview with a simple array of categories:
const categories = ['Rent', 'Groceries', 'Leisure'];
for (const category of categories) {
console.log(category); // iterates over the array's VALUES
}
for (const index in categories) {
console.log(index); // iterates over the INDICES ('0', '1', '2') - as strings!
}Tipp: Rule of thumb for later: use for...of for arrays and other iterable values (the values themselves), almost NEVER use for...in for arrays (it returns indices as strings and also iterates over inherited properties) – for...in is almost exclusively meant for object keys, see chapter 12.
break and continue
for (let month = 1; month <= 12; month++) {
if (month === 6) {
continue; // skips June, continues with July
}
if (month === 10) {
break; // ends the loop entirely starting at October
}
console.log(`Month ${month}`);
}
// Prints months 1-5 and 7-9Nested loops: a yearly overview
To wrap up phase 1, let's combine everything we've learned into a small yearly-overview simulation of our budget app:
const categories = ['Rent', 'Groceries', 'Leisure'];
for (let month = 1; month <= 3; month++) {
console.log(`--- Month ${month} ---`);
for (const category of categories) {
const isExpensive = category === 'Rent';
const note = isExpensive ? '(largest item)' : '';
console.log(` ${category} ${note}`);
}
}With that, phase 1 (fundamentals) is complete! In phase 2, we'll learn functions, arrays, and objects – and finally combine our loose transaction variables into a real data structure.