Loops
for, while, for...of, break, continue
Skills taught: js.loops, js.for, js.while, js.for-of
for loop — fixed count
// for (initialise; condition; update)
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// Counting down
for (let i = 5; i > 0; i--) {
console.log(i); // 5, 4, 3, 2, 1
}
// Loop over array by index
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]); // 0 apple, 1 banana, 2 cherry
}
for...of — iterate items
// Cleaner than indexed for — no index needed
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
console.log(fruit); // apple, banana, cherry
}
// Works on strings too
for (const char of 'hello') {
console.log(char); // h, e, l, l, o
}
// Get both index and value with entries()
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit); // 0 apple, 1 banana, 2 cherry
}
while loop — condition-based
// while — checks BEFORE each iteration
let count = 0;
while (count < 5) {
console.log(count); // 0, 1, 2, 3, 4
count++;
}
// do...while — checks AFTER (runs at least once)
let input;
do {
input = prompt('Enter a number above 10:');
} while (Number(input) <= 10);
break and continue
// break — exit the loop immediately
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i); // 0, 1, 2, 3, 4
}
// continue — skip this iteration, move to the next
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue; // skip even numbers
console.log(i); // 1, 3, 5, 7, 9
}
// Find first match and stop (efficient)
const users = [{id: 1, name: 'Ana'}, {id: 2, name: 'Ben'}, {id: 3, name: 'Cal'}];
let found = null;
for (const user of users) {
if (user.id === 2) { found = user; break; }
}
console.log(found); // {id: 2, name: 'Ben'}
Tip: For arrays, prefer array.find() over a for loop with break: const found = users.find(u => u.id === 2) — it's shorter and expresses intent clearly.
Frequently Asked Questions
What is the difference between for...of and for...in?
for...of iterates over iterable values (array items, string characters). for...in iterates over enumerable property KEYS of an object (including inherited ones). Use for...of for arrays; use Object.keys/values/entries for objects.
Can I use break inside a forEach loop?
No. break and continue only work in classic for, while, and for...of loops. forEach does not support breaking early. If you need early exit, use for...of, a classic for loop, or array.find() / array.some().