Imagine printing the 7 times table up to 10. You could write ten almost identical lines – or you could tell JavaScript “do this ten times”. A loop repeats a block of code while a condition stays true. JavaScript loops are how your programs process lists of products, build table rows, count characters and much more.
Every loop uses a condition, exactly like the ones in JavaScript Conditions. The loop keeps going while the condition is true and stops as soon as it becomes false.
The for loop
The classic for loop is best when you know how many times to repeat. Its brackets hold three parts separated by semicolons:
- Start – runs once before the loop begins, usually
let i = 1. - Condition – checked before every round; the loop stops when it is false, for example
i <= 10. - Update – runs after every round, usually
i++.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>for loop</title>
<style>
body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
</style>
</head>
<body>
<h2>7 times table</h2>
<pre id="out"></pre>
<script>
const number = 7;
let result = '';
for (let i = 1; i <= 10; i++) {
result += `${number} x ${i} = ${number * i}\n`;
}
document.getElementById('out').textContent = result;
</script>
</body>
</html>Each pass through the loop is called an iteration. We build up a string with += and write it to the page once at the end. Writing to the page inside the loop would also work, but collecting the result first is cleaner and faster when the list is long.
Tip: The counter is usually called i (short for index) by convention. Declaring it with let inside the brackets keeps it local to the loop, so it cannot clash with other variables.
Loops can also sit inside other loops. A loop inside a loop is called a nested loop: the inner loop runs completely for every single round of the outer one. Printing all the times tables from 1 to 10 would need an outer loop for the table number and an inner loop for the rows. Nested loops multiply the work quickly, so keep them small.
The while loop
A while loop has only a condition. Use it when you do not know in advance how many rounds you need – for example, “keep adding yearly interest until the savings cross a target”.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>while loop</title>
<style>
body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
</style>
</head>
<body>
<pre id="out"></pre>
<script>
let savings = 10000; // rupees
const target = 20000;
const interestRate = 0.07; // 7% per year
let years = 0;
while (savings < target) {
savings = savings + savings * interestRate;
years++;
}
document.getElementById('out').textContent =
`It takes ${years} years to reach Rs. ${target}.
Final amount: Rs. ${savings.toFixed(2)}`;
</script>
</body>
</html>There is also do … while, which checks the condition after each round, so the body always runs at least once. It is used far less often, for example when you must try something once before deciding whether to repeat it.
Watch out: If the condition never becomes false, you get an infinite loop and the browser tab freezes. In a while loop, always make sure something inside the loop moves you towards the end – here, savings grows every round. A missing i++ is the usual culprit.
Looping over a list with for…of
Very often you want to do something with every item in a list. You will study lists – called arrays – properly in JavaScript Arrays; for now, an array is just values inside square brackets. The for…of loop hands you each item in turn, with no counter to manage. It also works on strings, giving you one character at a time.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>for...of</title>
<style>
body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
</style>
</head>
<body>
<pre id="out"></pre>
<script>
const cities = ['Chennai', 'Madurai', 'Ooty', 'Puducherry', 'Tiruchirappalli', 'Vellore'];
let output = '';
for (const city of cities) {
if (city === 'Ooty') {
continue; // skip this one, go to the next city
}
if (city.length > 12) {
output += 'Name too long, stopping.\n';
break; // leave the loop completely
}
output += `${city} has ${city.length} letters\n`;
}
document.getElementById('out').textContent = output;
</script>
</body>
</html>Because each item gets a fresh variable in every round, you can declare it with const. Use the classic for loop instead when you need the position number of each item.
break and continue in JavaScript loops
breakexits the loop immediately. Use it when you have found what you were looking for and the remaining items do not matter.continueskips the rest of the current round and moves on to the next one. Use it to ignore items that do not apply.
Which loop should I use?
| Loop | Use it when… |
|---|---|
for | You know the number of repetitions, or you need the index |
for…of | You want each item of an array or each character of a string |
while | You repeat until something changes, and the count is unknown |
do…while | The body must run at least once |
for…in | You want the property names of an object (see Objects) – not for arrays |
Arrays also have built-in methods such as forEach(), map() and filter() that replace many hand-written JavaScript loops. They take a function as input, so we will meet them after the next lesson, JavaScript Functions.
