Loops repeat code.
Classic for loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Three parts: start (let i = 1), condition (i <= 5), step (i++).
for...of — loop over values
for (const fruit of ['apple', 'mango']) { ... }
Best for arrays and strings.
for...in — loop over keys
for (const key in student) { ... }
Used for object properties.
break and continue
breakexits the loop completelycontinueskips to the next round
Examples
Example — Multiplication table
HTML
<input id="n" type="number" value="7" style="width:60px">
<button onclick="table()">Show table</button>
<pre id="out"></pre>
<script>
function table() {
const n = Number(document.getElementById('n').value);
let text = '';
for (let i = 1; i <= 10; i++) {
text += `${n} x ${i} = ${n * i}\n`;
}
document.getElementById('out').textContent = text;
}
table();
</script>
Example — for...of with continue
HTML
<pre id="out"></pre>
<script>
const marks = [45, 82, 30, 91, 67];
let text = 'Passed marks:\n';
for (const m of marks) {
if (m < 33) continue; // skip failed marks
text += m + '\n';
}
document.getElementById('out').textContent = text;
</script>