
Printing 1 to 100 with a hundred console.log lines would be absurd — that's what loops are for. In this part of learn JavaScript from scratch you'll master the for loop, while, the modern for...of, and how to stop a loop early without creating the dreaded infinite loop.
This is Part 4 of Learn JavaScript from Scratch, continuing from Part 3.
1. Why loops exist
A loop repeats a block of code while a condition holds. Everything repetitive on a page is a loop underneath: rendering a list of 50 products, checking every answer in a quiz, summing a cart. Learn one pattern and you control them all: start → check → run the body → step → check again.
2. The classic for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0 1 2 3 4
}
Read the header as three slots separated by semicolons:
- start —
let i = 0: runs once before everything. - condition —
i < 5: checked before every round; loop ends the moment it's false. - step —
i++: runs after every round.
Why start at 0? Because positions in arrays and strings start at 0 (Part 6), so i = 0; i < length visits every position exactly once. Counting 1..n is just let i = 1; i <= n. Summing is the other bread-and-butter pattern:
let total = 0;
for (let i = 1; i <= 100; i++) total += i;
console.log(total); // 5050
3. while and do...while
while is a for loop with only the condition — you use it when you don't know how many rounds you'll need:
let hp = 100;
while (hp > 0) {
hp -= Math.floor(Math.random() * 30); // random damage
}
console.log("Game over");
do...while runs the body first and checks after, so the body always runs at least once — the natural shape for "ask until the input is valid":
let answer;
do {
answer = prompt("Type yes or no");
} while (answer !== "yes" && answer !== "no");
4. for...of - the modern loop over a collection
const fruits = ["apple", "mango", "banana"];
for (const fruit of fruits) {
console.log(fruit);
}
No counter, no length, no off-by-one errors: for...of hands you each element directly. It works on arrays, strings (character by character) and most collections. When you also need the position, wrap with entries():
for (const [i, fruit] of fruits.entries()) {
console.log(i, fruit); // 0 "apple" ...
}
Beware the lookalike for...in: it loops over keys/indexes as strings, not values, and is meant for plain objects. For arrays, use for...of.
5. break and continue
for (const n of numbers) {
if (n < 0) continue; // skip this round, go to the next
if (n === 0) break; // leave the loop entirely
console.log(n);
}
continue = "skip this item". break = "we're done" — typically the moment you've found what you were searching for, so you don't waste work scanning the rest.
6. Nested loops
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 3; col++) {
line += `(${row},${col}) `;
}
console.log(line);
}
The inner loop completes fully for each single step of the outer loop — 3 × 3 = 9 rounds here. That multiplication is why nesting gets slow fast: two nested loops over 1,000 items is a million rounds. Fine when needed (grids, pairs), but always ask if one pass could do it.
7. Common mistakes
- Off-by-one:
i <= arr.lengthgoes one past the end (last valid index islength - 1) and readsundefined. - Semicolon after the header:
for (…);— that stray semicolon is the loop body; the block below runs once. - Changing the wrong counter in nested loops (incrementing
iwhere you meantj) → infinite loop. - for...in on arrays: gives string indexes and can include extra properties. Use
for...of.
Practice: test what you learned
Q1. How many times does this run? for (let i = 0; i < 5; i++)
a) 4
b) 5
c) 6
d) Forever
Q2. Which loop guarantees its body runs at least once?
a) for
b) while
c) do...while
d) for...of
Q3. What does continue do inside a loop?
a) Skips the rest of the current round and starts the next one
b) Exits the loop entirely
c) Restarts the loop from the beginning
d) Pauses the loop for one second
Q4. What is the classic bug in for (let i = 0; i <= arr.length; i++) arr[i]?
a) It never runs
b) It skips the first element
c) The counter never increases
d) It goes one index past the end and reads undefined
Q5. Which is the right loop for "print every character of a string"?
a) for...in
b) for...of
c) do...while
d) switch
Q6. This loop freezes the page: let n = 10; while (n > 0) { console.log(n); }. Why?
a) console.log is slow
b) while cannot use variables
c) n never changes, so the condition never becomes false
d) 10 is too large a number
FAQ
When do I use for vs while?
Use for when the number of rounds is known or counted (0 to length). Use while when you loop until something happens (user quits, value found, data exhausted) and the count is unknown.
What is the difference between for...of and for...in?
for...of gives the VALUES of an iterable (arrays, strings). for...in gives the KEYS of an object as strings. Using for...in on arrays is a common bug source.
How do I loop over an object?
Either for...in (keys), or convert first: Object.keys(obj), Object.values(obj) or Object.entries(obj) with for...of. We practise this in Part 7.
My browser froze while practising loops - what do I do?
You made an infinite loop; close that tab and fix the condition or step. It happens to everyone once. The page freezes because JavaScript runs on one thread - the exact topic of our event loop video.
Learning with others? Join the CodingHumans WhatsApp community to get each new part of Learn JavaScript as soon as it goes live.
Comments
Post a Comment