JavaScript Loops: while, do/while and the Classic for Loop
How while, do/while and for loops run step by step, why let in a for header gives each iteration its own variable, multiple loop variables, infinite loops on purpose and by accident, off-by-one errors, modifying an array while looping over it, and how to choose the right loop.
kvi5hnuCode Sprout team member7 min readOn this page
Loops repeat code. JavaScript has five loop statements: while, do/while, for, for/of and for/in, plus for await for asynchronous data. This article covers the three condition-based loops, which keep going while a condition is true. The next article covers for/of and for/in, which walk through the values or keys of something.
while
while (condition) statement
while tests the condition; if it's truthy, it runs the body, then tests again, and so on. When the condition becomes falsy, the loop ends. If it's falsy from the start, the body never runs.
let countdown = 3;
const calls = [];
while (countdown > 0) {
calls.push(countdown);
countdown--; // something in the body must move toward the end
}
calls.push("liftoff");
console.log(calls.join(" "));
3 2 1 liftoff
while is the natural choice when you don't know in advance how many times to repeat: read input until it ends, retry until success, keep halving until a value is small enough.
let amount = 1000;
let years = 0;
while (amount < 2000) { // how long until an investment doubles at 7%?
amount *= 1.07;
years++;
}
console.log(years, amount.toFixed(2));
11 2104.85
do/while
do statement while (condition);
do/while runs the body first and tests the condition afterwards, so the body always runs at least once:
let attempts = 0;
do {
attempts++;
} while (false);
console.log(attempts);
let times = 0;
while (false) {
times++;
}
console.log(times);
1
0
It fits the "do it, then decide whether to repeat" pattern: show a menu and ask again if the choice is invalid, generate a random value until it meets a rule, fetch a page of results and continue while there's a next page. In practice it's the least used loop; most "at least once" cases are just as clear with while. Note that do/while ends with a semicolon.
The classic for loop
for (initialize; test; update) statement
Most loops have a counter that's set up once, tested before each pass and updated after each pass. for puts all three in one line:

- initialize runs once, before anything else. Usually it declares the counter.
- test is checked before every pass. If it's falsy, the loop ends.
- The body runs.
- update runs after each pass, then it's back to step 2.
for (let i = 1; i <= 3; i++) {
console.log("pass", i);
}
const letters = ["a", "b", "c"];
let reversed = "";
for (let i = letters.length - 1; i >= 0; i--) {
reversed += letters[i];
}
console.log(reversed);
pass 1
pass 2
pass 3
cba
Any of the three parts can be any expression, and you can manage several variables with the comma operator (article 30):
for (let left = 0, right = 10; left < right; left += 3, right -= 3) {
console.log(left, right);
}
0 10
3 7
This "two pointers" shape is common in algorithms, such as checking whether a string is a palindrome by comparing characters from both ends.
All three parts are optional. for (;;) with no test is an infinite loop, equivalent to while (true), ended from inside with break or return.
let in the header: a new variable for every pass
When the counter is declared with let, JavaScript creates a fresh copy of the variable for each iteration, initialized from the previous one. That matters as soon as a function created in the loop captures the counter:
const withLet = [];
for (let i = 0; i < 3; i++) {
withLet.push(() => i);
}
console.log(withLet.map((f) => f()).join(","));
const withVar = [];
for (var j = 0; j < 3; j++) {
withVar.push(() => j);
}
console.log(withVar.map((f) => f()).join(","));
0,1,2
3,3,3
With var there's a single variable for the whole loop, and every function sees its final value. This was one of the most famous JavaScript interview questions before ES2015, and it's the reason let exists in its current form (articles 26 and 27). The same applies to callbacks such as setTimeout or event handlers created in a loop.
Use let for loop counters, and const in for/of loops (next article). A const counter in a classic for loop doesn't work, because the update i++ would reassign it.
for or while?
They're interchangeable: for (init; test; update) body behaves almost exactly like init; while (test) { body; update; }. The one difference is continue (article 43): in a for loop, continue still runs the update, while in the while version it would skip the update and could loop forever. Use for when there's a clear counter, and while when the loop runs until something happens.
Infinite loops
An infinite loop is sometimes intended: a game loop, a server waiting for connections, a worker processing a queue, always with a break, return or await inside. Usually, though, it's a bug, and in a browser it freezes the page, because JavaScript runs on a single thread (part 13).
The usual causes:
let value = 0.1;
let steps = 0;
while (value !== 1 && steps < 20) { // without the steps guard, this never stops
value += 0.1;
steps++;
}
console.log(steps, value);
20 2.1000000000000005
- The condition never changes: forgetting
i++, or updating the wrong variable. - An exact comparison that's never hit:
0.1added ten times isn't exactly 1 (article 12), so!== 1stays true forever. Use<or<=for loop conditions. - Updating in the wrong direction:
for (let i = 10; i > 0; i++). - The data grows as fast as the loop advances, covered below.
If your page freezes while testing, the browser will eventually offer to stop the script; in Node, press Ctrl+C.
Off-by-one errors
Arrays are indexed from 0 to length - 1. The standard loop is for (let i = 0; i < arr.length; i++) with <, not <=:
const scores = [5, 6, 7];
for (let i = 0; i <= scores.length; i++) { // <= runs one time too many
if (scores[i] === undefined) console.log("read past the end at index", i);
}
read past the end at index 3
Reading past the end of an array doesn't throw: it gives undefined, which then quietly causes NaN or a TypeError later. When you only need the elements, for/of (next article) removes the index and the risk entirely.
Changing an array while looping over it
A classic loop re-reads arr.length on every test, so adding or removing elements during the loop changes what it visits:
const forward = [1, 2, 2, 3];
for (let i = 0; i < forward.length; i++) {
if (forward[i] === 2) forward.splice(i, 1); // the next element shifts into slot i and is skipped
}
console.log(forward);
const backward = [1, 2, 2, 3];
for (let i = backward.length - 1; i >= 0; i--) {
if (backward[i] === 2) backward.splice(i, 1); // shifting only affects slots already visited
}
console.log(backward);
console.log([1, 2, 2, 3].filter((n) => n !== 2)); // usually the best answer
[ 1, 2, 3 ]
[ 1, 3 ]
[ 1, 3 ]
Looping backwards fixes in-place removal. But building a new array with filter is clearer and avoids the problem altogether. Similarly, pushing to an array inside a loop over that array can make the loop run longer than intended, or forever.
Choosing a loop
| Situation | Best fit |
|---|---|
| Visit each element of an array, string, Map or Set | for/of (article 42), or array methods like forEach, map |
| You need the index too | for/of over arr.entries(), or a classic for |
| Count, step by 2, go backwards, two pointers | classic for |
| Repeat until something happens | while |
| Do something, then decide whether to repeat | do/while |
| Transform or select elements | map, filter, reduce (part 7) |
Common questions
Is a classic for loop faster than for/of or forEach?
Modern engines optimize all of them well, and the differences rarely matter outside hot paths over large arrays. Write the clearest loop first, then measure if performance becomes a concern.
Should I cache arr.length in a variable before the loop?
It was common advice for old engines. Today, reading length is very cheap, and caching it is only needed when the array changes during the loop and you want the original length.
Can I declare the counter outside the loop?
Yes: let i; for (i = 0; i < n; i++) {...} leaves i available after the loop, for example to know where a search stopped. Inside the header is better when you don't need it afterwards, because it keeps the variable's scope small.
How do I loop a fixed number of times without a counter I use?
for (let i = 0; i < n; i++) is the usual way. Array.from({ length: n }, (_, i) => ...) builds an array directly when you're collecting results.
Summary
while (test)checks before each pass and may run zero times;do { } while (test);always runs at least once.for (init; test; update)runsinitonce, then repeats test → body → update.letin aforheader gives each iteration its own variable, so closures keep their own values;varshares one variable.- Prevent infinite loops: make sure the condition changes, use
</<=rather than exact comparisons with floats, and don't grow the data you're looping over. - Loop with
i < arr.length, not<=; preferfor/ofwhen you don't need the index. - When removing elements, loop backwards or, better, use
filter.
Practice Questions
How many times does the body run?
let n = 10;
do {
n++;
} while (n < 5);
Answer
Once. The body runs before the first test; n becomes 11, 11 < 5 is false, and the loop ends.
What does this print?
let s = "";
for (let i = 0; i < 10; i += 3) s += i;
console.log(s);
Answer
"0369". i takes the values 0, 3, 6 and 9; at 12 the test fails. s is a string, so += concatenates.
Write a loop that finds the smallest power of 2 that is at least 1000.
Answer
let p = 1; while (p < 1000) p *= 2; leaves p at 1024. A while fits because the number of steps isn't known in advance.
Five buttons are created in this loop. What does every button show, and what's the fix?
for (var i = 0; i < 5; i++) {
buttons[i].onclick = () => alert(i);
}
Answer
Every button shows 5: there's one var i, and by the time anyone clicks, the loop has finished and i is 5. Use let i so each iteration, and each handler, gets its own i.
Previous: JavaScript switch Statement: case Matching, Fall-Through, default and Alternatives
Next: JavaScript for...of and for...in Loops: Iterating Arrays, Strings, Maps and Object Keys

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.