Loops
A loop runs the same block of code repeatedly, either a fixed number of times, once for each item in a collection, or until a condition stops being true. Loops let you print a times table, total the prices in a cart, or process every row of data without writing the same line over and over. JavaScript has several loop forms, and each one fits a particular situation.
The counting loop: for
The classic for loop has three parts in its parentheses: a starting statement, a condition checked before every pass, and an update that runs after every pass.
// Counting
for (let i = 1; i <= 5; i++) {
console.log(`7 x ${i} = ${7 * i}`);
}
// Looping over array values
const prices = [120, 80, 300];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(total); // 500
// Looping over object keys
const stock = { pens: 40, books: 12 };
for (const item in stock) {
console.log(item, stock[item]);
}
// Repeat until a condition changes
let attempts = 0;
while (attempts < 3) {
attempts++;
}
// Runs at least once
let input;
do {
input = getNextValue();
} while (input !== 'quit');
Picking the right loop
| Loop | Best for |
|---|---|
for | Counting, or when you need the index and control over steps |
for...of | Values of arrays, strings, Sets, Maps and NodeLists |
for...in | Keys of a plain object |
while | Repeating until something changes, when the count is unknown |
do...while | Like while, but the body must run at least once |
Arrays also have methods such as forEach, map and filter that loop for you. They are often clearer for transforming data, but they cannot be stopped early with break, so a for...of loop is better when you want to stop at the first match.
Controlling the flow: break and continue
break exits the loop immediately. Use it when you have found what you were looking for. continue skips the rest of the current pass and moves on to the next one, which is handy for ignoring invalid items. For example, inside a loop over orders, if (order.cancelled) continue; skips cancelled orders without nesting the rest of the code inside an if.
Bugs that show up in loops
Infinite loops. If the condition never becomes false, the loop runs forever and the browser tab freezes. This usually happens when you forget to update the counter in a while loop, or update the wrong variable. Check that something inside the loop moves it toward the end.
Off-by-one errors. Arrays start at index 0 and end at length - 1. Writing i <= arr.length runs one extra time and reads undefined. Use i < arr.length.
Using for...in on arrays. for...in gives keys as strings ("0", "1"), can include inherited properties, and is not meant for arrays. Use for...of for values, or a counting for loop when you need the index. If you need both, for (const [i, value] of arr.entries()) gives you each.
Changing an array while looping. Removing items from the array you are looping over shifts the remaining items and skips some. Build a new array with filter instead, or loop backwards.
Summary
Use for when counting, for...of for values, for...in for object keys, and while when you do not know how many passes you need. Always make sure the loop has a clear way to finish.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.