JavaScript Loops Tutorial: for, while & do-while
Master every JavaScript loop type in one guide. Covers for loops, while loops, do-while loops, for...in, for...of, break and continue statements, nested loops, performance tips, and common mistakes.
Loops let you run a block of code repeatedly without writing it out multiple times. JavaScript provides several loop types, each suited to different situations. A for loop is ideal when you know how many iterations you need, a while loop works best when the stopping condition depends on runtime data, and a do-while loop guarantees at least one execution before checking the condition.
This tutorial covers every loop type in JavaScript, with real code examples, comparison tables, and performance guidance so you can pick the right loop for any task.
The for Loop
The for loop is the most common loop in JavaScript. It packs initialization, condition, and update into a single line.
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`);
}
// Iteration 0
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4Anatomy of a for Loop
| Part | Purpose | Example |
|---|---|---|
| Initialization | Runs once before the loop starts | let i = 0 |
| Condition | Checked before each iteration; loop stops when false | i < 5 |
| Update | Runs after each iteration | i++ |
| Body | The code that executes on each iteration | console.log(i) |
Looping Through Arrays
The for loop is the standard way to iterate over arrays:
const languages = ["JavaScript", "Python", "Go", "Rust"];
for (let i = 0; i < languages.length; i++) {
console.log(`${i + 1}. ${languages[i]}`);
}
// 1. JavaScript
// 2. Python
// 3. Go
// 4. RustLooping in Reverse
const scores = [88, 92, 75, 100, 67];
for (let i = scores.length - 1; i >= 0; i--) {
console.log(`Score ${i}: ${scores[i]}`);
}
// Score 4: 67
// Score 3: 100
// Score 2: 75
// Score 1: 92
// Score 0: 88The while Loop
A while loop runs as long as its condition is true. Use it when you do not know in advance how many iterations you need.
let attempts = 0;
let success = false;
while (!success) {
attempts++;
// Simulate a random success on each try
success = Math.random() > 0.7;
console.log(`Attempt ${attempts}: ${success ? "Success!" : "Failed"}`);
}
console.log(`Succeeded after ${attempts} attempts`);Reading User Input with while
const tasks = [];
let input = "buy groceries";
// Simulating a loop that processes entries until empty
while (input !== "") {
tasks.push(input);
// In a real app, this would come from prompt() or readline
input = tasks.length >= 3 ? "" : `task ${tasks.length + 1}`;
}
console.log("Tasks:", tasks);
// Tasks: ["buy groceries", "task 2", "task 3"]The do-while Loop
The do-while loop always runs the body at least once before checking the condition. This is useful for menus, input validation, and retry logic.
let number;
let guessCount = 0;
const target = 7;
do {
// Simulate guesses
number = Math.floor(Math.random() * 10) + 1;
guessCount++;
console.log(`Guess ${guessCount}: ${number}`);
} while (number !== target);
console.log(`Found ${target} in ${guessCount} guesses`);for...in and for...of Loops
for...in (Object Properties)
The for...in loop iterates over the enumerable property keys of an object:
const user = { name: "Alice", age: 28, role: "developer" };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
// name: Alice
// age: 28
// role: developerfor...of (Iterable Values)
The for...of loop iterates over the values of any iterable (arrays, strings, Maps, Sets):
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// cherry
// Works with strings too
for (const char of "Hello") {
console.log(char);
}
// H, e, l, l, o| Feature | for...in | for...of |
|---|---|---|
| Iterates over | Object property keys (strings) | Iterable values (array elements, characters) |
| Works with arrays | Yes, but returns index strings | Yes, returns actual values |
| Works with objects | Yes (primary use case) | No (objects are not iterable by default) |
| Includes inherited props | Yes (use hasOwnProperty to filter) | No |
| Best for | Plain objects | Arrays, strings, Maps, Sets |
Break and Continue
break: Exit a Loop Early
The break statement stops the loop entirely:
const numbers = [3, 7, 12, 5, 18, 2, 9];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 10) {
console.log(`First number > 10: ${numbers[i]} at index ${i}`);
break;
}
}
// First number > 10: 12 at index 2continue: Skip to the Next Iteration
const scores = [88, -1, 92, 0, 75, -3, 100];
const validScores = [];
for (let i = 0; i < scores.length; i++) {
if (scores[i] <= 0) {
continue; // Skip invalid scores
}
validScores.push(scores[i]);
}
console.log(validScores); // [88, 92, 75, 100]Nested Loops
Nested loops place one loop inside another. The inner loop runs to completion for every iteration of the outer loop.
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let total = 0;
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
total += matrix[row][col];
}
}
console.log(`Matrix sum: ${total}`); // Matrix sum: 45Labeled Break with Nested Loops
const grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let found = false;
const target = 5;
outerLoop:
for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < grid[r].length; c++) {
if (grid[r][c] === target) {
console.log(`Found ${target} at [${r}][${c}]`);
found = true;
break outerLoop;
}
}
}
// Found 5 at [1][1]Loop Performance Tips
Following these guidelines keeps your loops fast, especially when processing large arrays:
- Cache the array length in a variable instead of reading
.lengthon every iteration. - Avoid creating functions inside loops. Define the function once outside, then reference it.
- Use
breakto exit early when you have found what you need. - Prefer array methods like map and filter for transformations; use
forloops when raw speed matters. - Watch for infinite loops where the condition never becomes false. See how to avoid infinite loops for common causes and fixes.
// Slow: reads .length every iteration
for (let i = 0; i < hugeArray.length; i++) { /* ... */ }
// Faster: caches length
for (let i = 0, len = hugeArray.length; i < len; i++) { /* ... */ }Common Mistakes
Off-by-One Errors
const items = ["a", "b", "c"];
// Bug: i <= items.length goes one index too far
for (let i = 0; i <= items.length; i++) {
console.log(items[i]); // Last iteration: undefined
}
// Fix: use strict less-than
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}Modifying an Array While Looping
const numbers = [1, 2, 3, 4, 5];
// Bug: removing elements shifts indices, skipping items
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
numbers.splice(i, 1); // Removes element, shifts array
}
}
console.log(numbers); // [1, 3, 5] -- looks correct here, but fragile
// Fix: loop in reverse when removing
const nums = [1, 2, 3, 4, 5];
for (let i = nums.length - 1; i >= 0; i--) {
if (nums[i] % 2 === 0) {
nums.splice(i, 1);
}
}
console.log(nums); // [1, 3, 5]Using var Instead of let
// Bug: var is function-scoped, not block-scoped
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Prints: 3, 3, 3 (all reference the same i)
// Fix: let creates a new binding per iteration
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 100);
}
// Prints: 0, 1, 2Choosing the Right Loop
| Scenario | Recommended Loop |
|---|---|
| Known number of iterations | for |
| Condition depends on runtime data | while |
| Must run at least once | do-while |
| Iterating object properties | for...in |
| Iterating array/string values | for...of |
| Transforming array into new array | .map() |
| Filtering elements | .filter() |
| Accumulating a single result | .reduce() |
Rune AI
Key Insights
- for loops excel at index-based iteration: use them when you know the start, end, and step ahead of time.
- while and do-while handle dynamic conditions: while checks before running, do-while guarantees at least one execution.
- for...of is the cleanest iterable loop: it works with arrays, strings, Maps, and Sets and gives you values directly.
- break and continue control flow within loops: break exits entirely, continue skips to the next iteration.
- Array methods complement loops: use map, filter, and reduce for declarative data transformations, and for loops for performance-critical or side-effect-heavy operations.
Frequently Asked Questions
What is the difference between for, while, and do-while loops?
Should I use for loops or array methods like map and filter?
How do I avoid infinite loops in JavaScript?
What is the difference between for...in and for...of?
Can I nest different types of loops?
Conclusion
JavaScript gives you multiple loop types for different situations. For loops handle known iteration counts, while loops handle dynamic conditions, and do-while loops guarantee at least one execution. Combined with for...in for objects, for...of for iterables, and array methods for functional transformations, you have a complete toolkit for any repetitive operation. The key is matching the right loop type to your specific use case and avoiding common traps like off-by-one errors, var scoping issues, and infinite loops.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.