Why loops?
Loops repeat code so you do not have to write it many times.
for loop
<script>
for (let i = 1; i <= 5; i++) {
document.write("Line " + i + "<br>");
}
</script>A for loop has three parts: start (let i = 1), condition (i <= 5) and step (i++).
while and do while
let n = 3;
while (n > 0) {
console.log(n);
n--;
}
let x = 0;
do {
console.log("Runs at least once");
x++;
} while (x < 1);for…of (values) and for…in (keys)
const fruits = ["mango", "banana", "apple"];
for (const f of fruits) {
console.log(f);
}
const student = { name: "Asha", age: 20 };
for (const key in student) {
console.log(key, student[key]);
}break and continue
for (let i = 1; i <= 10; i++) {
if (i === 3) continue; // skip 3
if (i === 6) break; // stop at 6
console.log(i);
}Example: multiplication table
<script>
const num = 7;
for (let i = 1; i <= 10; i++) {
document.write(num + " x " + i + " = " + num * i + "<br>");
}
</script>Note: A loop whose condition never becomes false runs forever and can freeze the page. Always make sure the loop moves toward its end.
Practice
Print the sum of numbers from 1 to 100, and print the numbers from 1 to 50 that are divisible by both 3 and 5.