Web Development - JavaScript Loops
JavaScript Loops
Loops let you run the same block of code multiple times automatically. They are useful for repeating actions such as counting numbers, listing items, or processing data.
The for Loop
A for loop repeats a block of code a specific number of times.
Syntax
for (initialization; condition; increment) {
// code to run each time
}
- initialization sets a starting value (like let i = 0)
- condition defines how long the loop runs
- increment updates the variable after each run
Example
Count from 1 to 5:
let text = "";
for (let i = 1; i <= 5; i++) {
text += "Count: " + i + "<br>";
}
Try it Yourself »
The loop starts at 1 and runs until i becomes greater than 5.
Each time, it adds one to i and builds a string of results.
The while Loop
A while loop runs a block of code as long as a condition is true.
Syntax
while (condition) {
// code to run while condition is true
}
The loop checks the condition before each run. If the condition becomes false, the loop stops.
Example
Count down from 5:
let n = 5;
let text = "";
while (n > 0) {
text += n + "<br>";
n--;
}
Try it Yourself »
This loop runs while n is greater than 0.
Each time, it decreases n by one.
The do...while Loop
A do...while loop runs the code at least once, even if the condition is false.
Syntax
do {
// code to run
} while (condition);
The code inside do runs first.
Then JavaScript checks the condition to see if it should repeat.
Example
Repeat until number is less than 5:
let i = 0;
let text = "";
do {
text += i + "<br>";
i++;
} while (i < 5);
Try it Yourself »
Even if i starts higher than 5, this loop will still run once before stopping.
Loop Control
You can control loops with break and continue.
break- stops the loop completelycontinue- skips the current round and moves to the next one
Example
Skip 3 and stop before 5:
let text = "";
for (let i = 1; i <= 8; i++) {
if (i === 3) continue; // skip 3
if (i === 5) break; // stop before 5
text += i + "<br>";
}
Try it Yourself »
When i equals 3, the loop skips it.
When i equals 5, the loop stops completely.
Nested Loops
You can place a loop inside another loop. This is useful for things like creating tables or grids.
Example
Multiplication table:
let text = "";
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
text += i + " * " + j + " = " + (i * j) + "<br>";
}
}
Try it Yourself »
The outer loop runs 3 times, and inside it, the inner loop also runs 3 times - creating 9 results in total.
Summary
for- loop with a counter (runs a set number of times)while- loop that runs while a condition is truedo...while- similar towhile, but always runs once first- Use
breakandcontinueto control the flow
Next, you'll learn about JavaScript Arrays and Objects - how to store and organize multiple pieces of data.
Next » JavaScript Arrays and Objects