By the end of this lesson, you will be able to choose and write JavaScript loops that repeat a block of code while a condition remains true.
What it is
A loop is a control-flow structure that runs a block of code multiple times. In JavaScript, loops are useful when you need to repeat work until a condition becomes false. The main loop forms are for, while, do...while, for...of, and for...in. A for loop is often used when the number of repetitions is known or when you need an index. A while loop is used when the stopping condition depends on data, user input, or program state. Related terms include iteration, loop body, loop variable, condition, increment, and termination.
Why it matters
- Process arrays and strings without copying code for each item.
- Build counters, timers, and repeated validation checks.
- Search through data until a match is found.
- Generate sequences, tables, or formatted output.
- Keep programs concise and easier to maintain.
Syntax or steps
The smallest useful pattern is a counted for loop:
for (let i = 0; i < 3; i++) {
// loop body
}
It has three parts:
- Initialization:
let i = 0creates a loop variable before the first iteration. - Condition:
i < 3is checked before each iteration. If false, the loop stops. - Update:
i++changes the loop variable after each iteration.
A while loop uses only a condition:
let count = 0;
while (count < 3) {
count++;
}
Example
const prices = [10, 20, 30];
let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
console.log(total); // 60
let attempts = 0;
while (attempts < 3) {
attempts++;
console.log("Attempt " + attempts);
}
Part by part:
prices.lengthmakes the loop run once for each array item.total += prices[i]adds the current price to the running total.- The
whileloop repeats untilattemptsreaches 3. attempts++is essential; without it, the condition would never become false.
Common mistakes
- Forgetting to update the loop variable. This can create an infinite loop. Fix it by incrementing or changing the condition inside the loop.
- Using the wrong comparison.
i <= array.lengthcan access an undefined item. Usei < array.lengthfor zero-based arrays. - Declaring the loop variable incorrectly. Using
varcan leak outside the loop. Preferletfor block scope. - Using
for...inon arrays. It iterates over property names, not values. Usefor...ofor a countedforloop for array values.
When to use it
Choose the loop that matches the data and stopping rule.
| Loop | Best for | Example |
|---|---|---|
for | Known count or index access | for (let i = 0; i < 3; i++) |
while | Unknown repetitions until condition false | while (score < 100) |
for...of | Array, string, or iterable values | for (const item of items) |
forEach | Simple array iteration without manual index | items.forEach(item => ...) |
Use for when you need an index or early exit with break. Use forEach when you only need to run a function for each array element and do not need break or return to control the loop.
Practice
Guided exercise: Write a loop that prints the numbers 1 through 5.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Expected output: 1, 2, 3, 4, 5.
Challenge: Given const names = ["Ada", "Lin", "Sam"];, print each name with its position starting at 1.
Solution hint: use for (let i = 0; i < names.length; i++) and print (i + 1) + ": " + names[i].
Expected output: 1: Ada, 2: Lin, 3: Sam.
Quick check
Question: What happens if the condition in a while loop never becomes false?
Answer: The loop runs forever, creating an infinite loop, unless the program is stopped or an error occurs.
Summary
JavaScript loops repeat work while a condition holds. Use for for counted or indexed repetition, while for condition-driven repetition, and for...of or forEach for iterating over values. Always make sure the loop can reach a stopping point.