JavaScript Loops
Loops run the same block of code again and again. Instead of writing ten lines that do the same thing, you write one loop that repeats ten times. That keeps code short, and when you need eleven trips instead of ten, you change one number instead of editing ten lines. The two loops you will use most are for and while.
The for loop has three parts in one line: a starting value, a condition, and an update. Each trip through the block is called an iteration. The classic beginner error here is the off-by-one bug: using <= when the count should use <, or the reverse, so the loop runs one time too many or one too few.
The while loop is simpler but easier to get wrong. It repeats while a condition stays true, and you must move the value toward the end yourself, inside the block. If you forget, the condition never becomes false and the loop never stops. That is an infinite loop, and it will freeze the page. Always make sure the condition can eventually turn false.
Looping through arrays
Loops pair perfectly with arrays. Use the array length as the stop condition, and read each item with its index. The condition i < names.length is the safe pattern; i <= names.length is off by one and reads one item past the end, which comes back as undefined.
const names = ["Ada", "Grace", "Linus"];
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
break and continue
break stops the loop early, and continue skips the rest of the current trip and jumps to the next one. Use break when you found what you were looking for, and continue to skip values you do not want to handle.
for (let i = 1; i <= 10; i++) {
if (i === 3) {
continue; // skip 3
}
if (i === 7) {
break; // stop at 7
}
console.log(i);
}
Syntax
for (let i = 0; i < 5; i++) {
console.log("Trip number " + i);
}
for (i<=array.length) Reads Past End
Arrays end at length-1 — using <= reads undefined. Use i < array.length.
for(let i=0; i<arr.length; i++)
Good to know
- for loops repeat a set number of times with a counter.
- while loops run while a condition stays true; update the counter inside.
- i < length, not <=, or you read past the end of the array.
- break stops early; continue skips one trip.