JavaScript has four different loop forms, and they are not interchangeable. The classic for loop counts. The while loop repeats until a condition changes. for...of walks through the values of a list, and for...in walks through the keys of an object. Mixing up the last two is the single most common loop bug in JavaScript, and this lesson makes sure you never do it.
The previous lesson in this module covered "if/else and switch: Decisions in JavaScript", and this lesson is the last one in the JavaScript Operators and Control Flow module.
Which loop forms does JavaScript have?
| Form | Use it when |
|---|---|
for | You know how many times to repeat, or you need the index |
while | You repeat until something changes, and the count is not known |
do...while | The same as while, but the body must run at least once |
for...of | You want the values of something you can walk through, such as an array, a string, or a Set |
for...in | You want the keys of an object. Almost never for an array |
Pick the loop whose shape matches the problem, rather than the one that you happen to have typed before. That single habit removes most off-by-one errors before they can happen.
How does the classic for loop work?
There are three parts in the header, separated by semicolons. There is an initialiser that runs once, there is a condition that is checked before every round, and there is an update that runs after every round.
const days = ['Mon', 'Tue', 'Wed'];
for (let i = 0; i < days.length; i += 1) {
console.log((i + 1) + '. ' + days[i]);
}
The output is three lines. They are 1. Mon, 2. Tue, and 3. Wed.
The classic mistake here is writing i <= days.length. The array has three items at the positions 0, 1, and 2, so the position 3 is undefined, and your loop prints a fourth line with nothing in it. Another common mistake is starting the index at 1 and then using days[i], which skips the first element. Whenever you use an index, remember that the first element is at the index 0.
Declaring the counter with let inside the header is deliberate. It gives each loop its own counter, and it keeps that counter out of the surrounding code.
When should I use while instead?
Use while when the number of repetitions depends on something that you cannot know in advance. A retry loop is a good example, and so is a queue that drains while you process it, or a poll that waits for a job to finish.
let remaining = 3;
while (remaining > 0) {
console.log('countdown:', remaining);
remaining -= 1;
}
let attempt = 0;
do {
attempt += 1;
console.log('attempt:', attempt);
} while (attempt < 2);
The countdown prints 3, 2, and 1. Then the do...while loop prints attempt 1 and attempt 2, because it checks the condition at the end of the body, so the body always runs at least once. That difference matters when the first pass has to happen, such as validating a form before you even know whether a second attempt is needed.
Here is the same do...while showing the difference more clearly.
let value = 10;
do {
console.log('ran with value:', value);
value += 1;
} while (value < 5);
It prints one line, which is ran with value: 10, even though the condition is false from the very start. A while loop with the same condition would print nothing at all.
Whatever you choose, make sure that the loop terminates. A while (true) loop with no break inside it locks up the page, and the browser will eventually offer to kill the tab.
What does for...of give me?
It gives you the values, in order, from anything that you can walk through. It removes the index arithmetic completely, which is why it replaced the classic for loop for most work with arrays.
const languages = ['JavaScript', 'Python', 'Go'];
for (const language of languages) {
console.log(language);
}
for (const letter of 'JS') {
console.log(letter);
}
The first loop prints the three language names. The second prints J and S, because a string can be walked through as well. Sets, Maps, and the entries of an array can all be walked through, so the same form works across all of them.
When you need the position as well, for...of does not give it to you directly. You can get the position with the entries method of the array, which produces index and value pairs.
const days = ['Mon', 'Tue'];
for (const pair of days.entries()) {
console.log(pair[0], pair[1]);
}
That prints 0 Mon and 1 Tue. The array module later in this tutorial covers the array methods in full, including the difference between for...of and forEach.
Why is for...in dangerous for arrays?
Because it gives you the keys, and for an array the keys are the string indices. They are strings and not numbers, and if the array has extra properties then those come along too.
const scores = { ana: 91, ben: 78, cy: 84 };
for (const name in scores) {
console.log(name + ': ' + scores[name]);
}
const days = ['Mon', 'Tue'];
for (const key in days) {
console.log(key, typeof key);
}
The first loop prints the three name and value pairs, which is exactly what you want for...in to do. The second prints 0 string and 1 string, which are the keys as strings. The values 'Mon' and 'Tue' never appear at all, and you had to read them back out with days[key] to get them in the first place.
Use for...in for objects and for...of for arrays. That one rule removes an entire family of bugs, including the ones where a string index quietly works in one place and then fails in another.
How do break and continue work?
break leaves the loop immediately. continue skips the rest of the current round and goes back to the top of the loop.
const numbers = [1, 2, 3, 4, 5, 6];
for (const number of numbers) {
if (number % 2 === 0) {
continue;
}
console.log('odd:', number);
}
for (const number of numbers) {
if (number > 4) {
break;
}
console.log('before the break:', number);
}
The first loop prints odd: 1, odd: 3, and odd: 5, because the even numbers are skipped by the continue. The second loop prints before the break: 1 through before the break: 4, and then it stops at 5 because of the break.
How do I break out of a nested loop?
A break only leaves the loop that it is written in, so leaving two nested loops at the same time needs a label.
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
outer: for (const row of matrix) {
for (const value of row) {
if (value === 5) {
console.log('found 5, stopping');
break outer;
}
}
}
The label outer is attached to the outer loop, and break outer leaves both of them. The output is a single line, which is found 5, stopping.
Labels are powerful and easy to abuse, so use them when a nested loop genuinely needs to escape, and not as a general shortcut. If you find yourself labelling three levels deep, then the problem is usually that the work should be extracted into a function that returns early instead.
How to choose a loop
- Use the classic
forloop when you know the count or you need the index. - Use
whilewhen you repeat until a condition changes, and usedo...whilewhen the body has to run at least once. - Use
for...offor the values of an array, a string, a Set, or a Map. - Use
for...infor the keys of an object, and never for an array. breakexits a loop,continueskips one round, and a label letsbreakexit nested loops.- Every loop needs a path where its condition becomes false, so make sure the update really moves towards it.
Try it yourself: take a list of task names and write the same loop four different ways. Use the classic for loop with an index, then for...of, then forEach, and then map. Print each task together with its position in the output. Then change the list into an object that is keyed by task id, and see which of the four loops still makes sense. That experiment is the fastest way to understand the difference between values and keys.