Repeat with a measurable stopping condition
A loop needs an initial state, a condition and progress. for is convenient for counting; while fits a condition whose repetition count is unknown; do-while executes at least once before checking its condition.
let total = 0;
for (let number = 1; number <= 5; number += 1) {
total += number;
}
console.log(total); // 15
let remaining = 3;
while (remaining > 0) {
console.log(remaining);
remaining -= 1;
}The while example prints 3, 2 and 1. Removing its update creates an infinite loop. A long synchronous loop blocks the browser's main thread, so it can freeze input and rendering even if it eventually terminates.
Array bounds and useful iteration
const marks = [62, 75, 83];
for (let index = 0; index < marks.length; index += 1) {
console.log(index, marks[index]);
}
for (const mark of marks) {
console.log(mark);
}Indices run from zero to length-1. A condition using <= length reads one extra position, normally producing undefined. for...of reads iterable values; for...in enumerates enumerable property keys and is not the ordinary choice for array values.
do-while and flow control
let attempts = 0;
do {
attempts += 1;
} while (attempts < 1);
console.log(attempts); // 1break leaves the nearest loop. continue skips to the next iteration. In a while loop, make sure continue cannot bypass the only state update. Avoid mutating an array while traversing it until you understand how that affects the iteration.
Practice and answers
- Print even numbers from 2 through 10. Expect 2, 4, 6, 8, 10.
- Count multiples of 3 from 1 through 20. Answer: 6.
- Find a mark above 80 and break after the first match. The sample match is 83.
- Trace the index, current value and accumulator in a small table before running a new loop.
हिन्दी संकेत: हर iteration में condition बदलने की दिशा में progress होना चाहिए; browser को block करने वाले बड़े loops से बचें।