JavaScript Loops
Loops run the same code again and again, as long as a condition is true.
Why Loops?
Imagine printing roll numbers 1 to 100. Writing 100 lines is slow and boring. A loop does it in three lines.
The for Loop
Example
for (let i = 1; i <= 5; i++) {
console.log("Roll no " + i);
}Roll no 1 Roll no 2 Roll no 3 Roll no 4 Roll no 5
The for loop has three parts, separated by semicolons:
| Part | Example | Meaning |
|---|---|---|
| Start | let i = 1 | Runs once, before the loop starts |
| Condition | i <= 5 | Checked before every round; the loop stops when false |
| Step | i++ | Runs after every round |
A Times Table
Example
<!DOCTYPE html>
<html>
<body>
<h2>Table of 7</h2>
<p id="demo"></p>
<script>
let text = "";
for (let i = 1; i <= 10; i++) {
text += "7 x " + i + " = " + (7 * i) + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>Try it Yourself »The while Loop
while repeats as long as its condition is true. Use it when you do not know in advance how many rounds you need.
Example
let savings = 0;
let months = 0;
while (savings < 50000) {
savings += 8000;
months++;
}
console.log("Ali needs " + months + " months to save Rs " + savings);Ali needs 7 months to save Rs 56000
Always make sure the condition becomes false at some point. If it never does, you get an infinite loop and the browser tab freezes.
The do...while Loop
do...while runs the code once before checking the condition, so it always runs at least one time.
Example
let n = 10;
do {
console.log(n);
n++;
} while (n < 5);10
for...of: Loop Through Values
for...of gives each value of an array (or each character of a string):
Example
<!DOCTYPE html>
<html>
<body>
<ul id="menu"></ul>
<script>
const dishes = ["Nihari", "Haleem", "Karahi", "Biryani"];
let html = "";
for (const dish of dishes) {
html += "<li>" + dish + "</li>";
}
document.getElementById("menu").innerHTML = html;
</script>
</body>
</html>Try it Yourself »for...in: Loop Through Keys
for...in goes through the property names of an object:
Example
const fees = { html: 3000, css: 3000, javascript: 5000 };
for (const course in fees) {
console.log(course + " costs Rs " + fees[course]);
}break and continue
breakstops the loop completelycontinueskips the rest of this round and goes to the next one
Example
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
if (i > 7) break; // stop after 7
console.log(i);
}1 3 5 7
Which Loop Should I Use?
- A fixed number of times:
for - Every item in an array:
for...oforforEach() - Every key in an object:
for...in - Until something happens:
while
Exercise
Exercise
How many times does this loop run? for (let i = 0; i < 4; i++) { }
