How to Use Loops in JavaScript: while, for, break, continue, for...of, for...in and More
Programs constantly need to repeat actions. Process every item in a shopping cart. Check each character in a password. Retry a failed network request. Count down from ten. Without loops, you would need to write the same code hundreds or thousands of times. Loops let you write the code once and have the computer repeat it as many times as needed.
JavaScript provides several loop constructs, each suited to different situations. This guide covers every loop type in depth, from the fundamental while and for loops to the modern for...of iterator. You will learn how to control loop execution with break and continue, how to handle nested loops with labels, and how to avoid the most common loop-related bugs that waste developers' debugging time.
The while Loop
The while loop is the simplest loop structure. It repeats a block of code as long as a condition remains truthy.
Syntax
while (condition) {
// code to repeat
}
Before each iteration, the condition is evaluated. If it is truthy, the loop body executes. If it is falsy, the loop ends and execution continues with the code after the loop.
Basic Example
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
// Output: 1, 2, 3, 4, 5
console.log("Loop finished. Count is now:", count); // 6
Step-by-step execution:
Iteration 1: count=1, 1 <= 5 is true → log 1, count becomes 2
Iteration 2: count=2, 2 <= 5 is true → log 2, count becomes 3
Iteration 3: count=3, 3 <= 5 is true → log 3, count becomes 4
Iteration 4: count=4, 4 <= 5 is true → log 4, count becomes 5
Iteration 5: count=5, 5 <= 5 is true → log 5, count becomes 6
Check: count=6, 6 <= 5 is false → loop ends
When to Use while
Use while when you do not know in advance how many iterations you need:
// Roll a die until you get a 6
let rolls = 0;
let result;
while (result !== 6) {
result = Math.floor(Math.random() * 6) + 1;
rolls++;
console.log(`Roll ${rolls}: ${result}`);
}
console.log(`Got a 6 after ${rolls} rolls!`);
// Process user input until they type "quit"
let input = "";
while (input !== "quit") {
input = prompt("Enter a command (type 'quit' to exit):");
if (input !== "quit") {
console.log(`Processing: ${input}`);
}
}
console.log("Goodbye!");
Single-Line Body
Like if statements, single-line while bodies do not require braces, but you should always include them:
// Works but dangerous
while (count < 10) count++;
// Always use braces
while (count < 10) {
count++;
}
The do...while Loop
The do...while loop is a variation of while that always executes the body at least once before checking the condition.
Syntax
do {
// code to repeat (runs at least once)
} while (condition);
Notice the semicolon after the condition. This is required for do...while.
Basic Example
let count = 1;
do {
console.log(count);
count++;
} while (count <= 5);
// Output: 1, 2, 3, 4, 5
The Key Difference from while
With a regular while, the body might never execute if the condition is initially false. With do...while, the body always runs at least once:
// while: body never executes
let x = 10;
while (x < 5) {
console.log("This never runs");
}
// do...while: body executes once
let x = 10;
do {
console.log("This runs once!"); // Runs!
} while (x < 5);
// "This runs once!" is printed even though x (10) is not less than 5
Practical Use Cases
do...while is ideal when you need at least one execution, such as input validation:
let password;
do {
password = prompt("Create a password (minimum 8 characters):");
} while (password !== null && password.length < 8);
if (password === null) {
console.log("Registration cancelled");
} else {
console.log("Password accepted!");
}
// Menu system: always show the menu at least once
let choice;
do {
choice = prompt(
"Menu:\n1. View profile\n2. Settings\n3. Logout\n\nEnter your choice:"
);
switch (choice) {
case "1":
alert("Showing profile...");
break;
case "2":
alert("Opening settings...");
break;
case "3":
alert("Logging out...");
break;
default:
if (choice !== null) alert("Invalid choice, try again.");
}
} while (choice !== "3" && choice !== null);
The for Loop
The for loop is the most commonly used loop in JavaScript. It combines initialization, condition checking, and increment into a single, compact line.
Anatomy of a for Loop
for (initialization; condition; update) {
// loop body
}
| Part | Purpose | Example |
|---|---|---|
| Initialization | Runs once before the loop starts | let i = 0 |
| Condition | Checked before each iteration | i < 5 |
| Update | Runs after each iteration | i++ |
Basic Example
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
Execution flow:
1. Initialization: let i = 0
2. Condition check: 0 < 5? YES → run body (log 0)
3. Update: i++ (i becomes 1)
4. Condition check: 1 < 5? YES → run body (log 1)
5. Update: i++ (i becomes 2)
... continues ...
10. Condition check: 4 < 5? YES → run body (log 4)
11. Update: i++ (i becomes 5)
12. Condition check: 5 < 5? NO → loop ends
Common for Loop Patterns
Counting up:
for (let i = 1; i <= 10; i++) {
console.log(i); // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
}
Counting down:
for (let i = 10; i >= 1; i--) {
console.log(i); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
}
console.log("Liftoff!");
Stepping by values other than 1:
// Count by twos
for (let i = 0; i <= 20; i += 2) {
console.log(i); // 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
}
// Count by fives
for (let i = 0; i <= 100; i += 5) {
console.log(i); // 0, 5, 10, 15, ... 95, 100
}
Iterating over an array by index:
let fruits = ["apple", "banana", "cherry", "date"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i}: ${fruits[i]}`);
}
// 0: apple
// 1: banana
// 2: cherry
// 3: date
Iterating backward over an array:
let colors = ["red", "green", "blue"];
for (let i = colors.length - 1; i >= 0; i--) {
console.log(colors[i]);
}
// blue, green, red
Optional Parts
Every part of the for loop header is optional. You can omit any or all of them:
// Omit initialization (variable declared elsewhere)
let i = 0;
for (; i < 5; i++) {
console.log(i);
}
// Omit update (done inside the body)
for (let i = 0; i < 5;) {
console.log(i);
i++;
}
// Omit everything (infinite loop, be careful!)
for (;;) {
// Runs forever unless you break out
break; // Prevents infinite loop
}
Multiple Variables in for Loop
You can initialize and update multiple variables using the comma operator:
for (let i = 0, j = 10; i < j; i++, j--) {
console.log(`i=${i}, j=${j}`);
}
// i=0, j=10
// i=1, j=9
// i=2, j=8
// i=3, j=7
// i=4, j=6
Breaking Out of Loops with break
The break statement immediately terminates the loop and continues with the code after the loop.
Basic Usage
for (let i = 0; i < 100; i++) {
if (i === 5) {
break; // Exit the loop immediately
}
console.log(i);
}
// Output: 0, 1, 2, 3, 4
// Note: 5 is NOT printed because break runs before console.log