Careeroza
Loops
The for Loop
Example
for (let i = 1; i <= 5; i++) {
console.log("Row " + i);
}Output
Row 1 Row 2 Row 3 Row 4 Row 5
while and do...while
Example
while repeats as long as the condition is true; do...while always runs at least once:
let balance = 1000, years = 0;
while (balance < 2000) {
balance *= 1.1; // 10% interest
years++;
}
console.log(years + " years to double");
let tries = 0;
do {
tries++;
} while (tries < 3);
console.log("tries:", tries);Output
8 years to double tries: 3
for...of and for...in
Example
for...of loops over values of an iterable (arrays, strings); for...in loops over keys of an object:
const langs = ["HTML", "CSS", "JS"];
for (const lang of langs) console.log(lang);
const marks = { math: 90, science: 85 };
for (const subject in marks) console.log(subject, marks[subject]);Output
HTML CSS JS math 90 science 85
Note: Do not use for...in on arrays: it iterates keys as strings and can include inherited properties.
break and continue
Example
break leaves the loop; continue skips to the next iteration:
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);
}Output
1 3 5 7
Exercise
Exercise: Print the numbers from 1 to 15, but print "Fizz" for multiples of 3, "Buzz" for multiples of 5 and "FizzBuzz" for multiples of both.
Show answer
for (let i = 1; i <= 15; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}