Loops
Overview
Loops run a block of code again and again. Without them, printing the numbers 1 to 100 would take 100 lines. With a loop, it takes three:
for (let i = 1; i <= 100; i++) {
console.log(i);
}Each pass through a loop’s body is called an iteration. JavaScript has several kinds of loop; each suits a different job.
The for loop
for (let i = 1; i <= 3; i++) {
console.log(`Lap ${i}`);
}The brackets hold three parts, separated by semicolons:
- Start —
let i = 1runs once, before anything else. It creates the loop’s counter. - Check —
i <= 3is tested before each iteration. If it’s false, the loop ends. - Update —
i++runs after each iteration, moving the counter on.
The counter can count in any direction and by any step:
for (let i = 10; i > 0; i--) { /* 10, 9, … 1 */ }
for (let i = 0; i <= 100; i += 10) { /* 0, 10, 20, … 100 */ }Looping over an array by index
Arrays are numbered from 0, so the classic pattern starts at 0 and stops before length:
const colours = ['red', 'green', 'blue'];
for (let i = 0; i < colours.length; i++) {
console.log(i, colours[i]);
}Writing i <= colours.length is a common off-by-one mistake: the last iteration reads colours[3], which is undefined.
while and do…while
while repeats as long as a condition is true — useful when you don’t know how many rounds you’ll need:
let attempts = 0;
while (attempts < 3) {
attempts++;
console.log(`Attempt ${attempts}`);
}A more realistic example: keep halving a number until it’s small enough.
let size = 1000;
let steps = 0;
while (size > 1) {
size /= 2;
steps++;
}
console.log(steps); // 10do…while always runs at least once, because it checks the condition at the end:
let answer;
do {
answer = prompt('Type yes to continue');
} while (answer !== 'yes');Infinite loops
If a loop’s condition never becomes false, it runs forever and freezes the page:
let i = 0;
while (i < 5) {
console.log(i); // i never changes — infinite loop!
}Every while loop must change something that its condition depends on. If your browser tab locks up while you’re practising, an infinite loop is the usual suspect — close the tab and check your update step.
for…of
The easiest way to loop over the values of an array (or the characters of a string):
const topics = ['Loops', 'Functions', 'Objects'];
for (const topic of topics) {
console.log(topic);
}
for (const char of 'hey') {
console.log(char); // 'h', 'e', 'y'
}for…of works with anything iterable — arrays, strings, Maps, Sets and more (you’ll see how in Iterators and generators). Use const for the loop variable, since each iteration gets a fresh one.
Need the index too? Use entries() with destructuring:
for (const [index, topic] of topics.entries()) {
console.log(`${index + 1}. ${topic}`);
}for…in
for…in loops over an object’s keys:
const scores = { asha: 9, ravi: 7 };
for (const name in scores) {
console.log(name, scores[name]);
}
// asha 9
// ravi 7Don’t use
for…inon arrays. It gives you indexes as strings and can include extra properties. Usefor…ofinstead.
For objects, many developers prefer Object.entries() with for…of, which gives you the key and value together:
for (const [name, score] of Object.entries(scores)) {
console.log(name, score);
}break and continue
break stops the loop immediately. continue skips the rest of the current iteration and moves on to the next:
for (const n of [1, 2, 3, 4, 5]) {
if (n === 2) continue; // skip 2
if (n === 4) break; // stop at 4
console.log(n); // 1, 3
}break is ideal for searching — stop as soon as you’ve found what you need:
const users = ['ravi', 'asha', 'mina'];
let found = false;
for (const user of users) {
if (user === 'asha') {
found = true;
break; // no need to check 'mina'
}
}Nested loops
A loop inside a loop runs the inner loop completely for every iteration of the outer one — useful for grids and tables:
for (let row = 1; row <= 3; row++) {
let line = '';
for (let col = 1; col <= 3; col++) {
line += `${row * col}\t`;
}
console.log(line);
}
// 1 2 3
// 2 4 6
// 3 6 9break and continue only affect the innermost loop. To break out of an outer loop, give it a label: outer: for (…) { … break outer; }. Labels are rare; often moving the loops into a function and using return is clearer.
Which loop should I use?
| You want to… | Use |
|---|---|
| Repeat a known number of times, or count | for |
| Go through each item in an array or string | for…of |
| Repeat until something changes, count unknown | while |
| Run at least once, then maybe repeat | do…while |
| Go through an object’s keys | for…in or Object.keys() |
You’ll also meet array methods such as forEach, map and filter in the Arrays chapter. They replace many loops with something shorter and clearer.
Sum the even numbers
Write sumEvens(n) that adds up every even number from 1 to n. Then write countdown(n) that returns an array counting down from n to 1.
function sumEvens(n) {
// your code here
}
function countdown(n) {
// your code here
}
sumEvens(10); // 30
countdown(3); // [3, 2, 1]function sumEvens(n) {
let total = 0;
for (let i = 2; i <= n; i += 2) {
total += i;
}
return total;
}
function countdown(n) {
const result = [];
for (let i = n; i >= 1; i--) {
result.push(i);
}
return result;
}Summary
foris best when you know how many times to repeat: start, check, update.whilerepeats while a condition holds;do…whilealways runs at least once.for…ofloops over the values of arrays, strings and other iterables.for…inloops over an object’s keys — don’t use it on arrays.breakstops a loop;continueskips to the next round. Make sure every loop can end.