JavaScript Loops — Infinite While That Crashed a Dashboard
CPU at 100% on a single core, event loop lag >10s—from a while loop missing its increment.
- A loop repeats a block of code until a condition is false or all items are processed.
for: Use when you know the exact count (e.g., iterate an array with index).while: Use when the condition depends on runtime state (e.g., waiting for user input).forEach/for...of: Cleaner array iteration, butforEachlacksbreak/continue.- Performance:
foris fastest in tight loops;forEachhas function call overhead (~50ns per item). - Production trap: An infinite
whileloop freezes the event loop — always ensure the condition changes. - Biggest mistake: Using
<=instead of<in array loops — leads toundefinedaccess.
Imagine you're stuffing 100 envelopes for a birthday party. You wouldn't write a separate instruction for each envelope — you'd write one instruction: 'Stuff an envelope, seal it, repeat until all 100 are done.' That's exactly what a loop is in JavaScript. It's one set of instructions that the computer repeats automatically until a condition is met, saving you from writing the same code over and over again.
Every app you've ever used relies on loops. When Instagram loads your feed, a loop runs through every post and renders it on screen. When Spotify builds your playlist, a loop processes every song. When a game checks if you've been hit by an enemy, a loop is running dozens of times per second. Loops are not just a feature of JavaScript — they are one of the fundamental building blocks of everything a program does.
Here's what most tutorials don't tell you: picking the wrong loop can cost you real production issues — from frozen browser tabs to silent data corruption. Understanding when to use each variant is what separates a script from a robust application.
The for Loop — When You Know Exactly How Many Times to Repeat
The for loop is the most common loop you'll write. You reach for it when you know upfront how many times something needs to happen — print 5 messages, process 10 orders, light up 7 checkboxes. Think of it like a strict gym trainer who says: 'Do exactly 10 reps, then stop.' No more, no less.
A for loop has three parts packed into one line, separated by semicolons. First, a starting point — you create a counter variable, usually called i, and set it to 0 (because JavaScript lists start counting from 0, not 1). Second, a condition — the loop keeps running as long as this condition is true. Third, an update — after each loop, you change the counter, usually by adding 1.
When the condition becomes false, JavaScript exits the loop and moves on. That's the whole mechanic. Everything else is just variations on this pattern.
Production reality: The for loop is the only loop that gives you full control — you can decrement, skip steps, or iterate backwards. It's also the fastest loop in JavaScript because it avoids any function call overhead. Use it when performance is critical, like in rendering loops or when processing large arrays.
< array.length for array iteration; use <= only for fixed-count loops.<. Fixed count? Use <=.The while Loop — When You Don't Know How Many Times to Repeat
The while loop is what you use when you can't predict upfront how many times you'll need to repeat something. The loop just keeps going as long as a condition stays true, and stops the moment it becomes false.
A great real-world analogy: imagine you're fishing. You don't say 'I'll cast exactly 7 times.' You say 'I'll keep casting until I catch a fish.' You don't know if that's 2 casts or 200. That uncertainty is exactly when while is the right tool.
In code, while loops are common for things like: keep asking the user for a password until they get it right, keep downloading data until the file is complete, or keep running a game loop until the player loses. The key discipline with while loops is that something inside the loop must eventually make the condition false — otherwise you get an infinite loop, and your program freezes forever.
Performance note: Because the condition is re-evaluated each iteration, while loops can be slightly slower than for loops if the condition involves a complex expression. But in practice, the overhead is negligible for most applications.
let safe = 0; while (cond && safe++ < 1e6) { ... }.forEach and for...of — The Modern, Readable Way to Loop Arrays
Once you understand for loops, JavaScript gives you two cleaner tools specifically designed for looping through arrays and collections: forEach and for...of. They exist because the classic for loop, while powerful, has a lot of visual noise — the counter, the condition, the increment. When all you want to do is 'go through every item in this list,' there's a simpler way.
forEach is a method that lives on every array. You hand it a function, and it calls that function once for each item, automatically passing in the item, its index, and the whole array if you need them. It's expressive — reading it out loud almost sounds like plain English: 'for each order in orders, do this thing.'
for...of is even simpler — it's a loop syntax (like for) but designed for collections. You get the value directly without index gymnastics. Use for...of when you just need the values. Use forEach when you want the built-in index parameter without extra setup. Neither can be 'broken out of' easily with break — use a classic for loop if you need to exit early.
Performance reality: forEach incurs a function call overhead (~50ns per item on V8). For arrays under 10,000 items, it's unnoticeable. For performance-critical hot paths, a for loop is still faster. for...of is also slightly slower than a for loop but more readable.
break, continue, or return to exit early.return inside — that return exits only the callback, not the loop.if (condition) return; in forEach expecting early exit, but the loop continues.break and continue; forEach does not.break.do...while — The Loop That Always Runs at Least Once
There's one more loop worth knowing: do...while. It's the least common, but it solves a specific problem elegantly. Every other loop checks its condition before running the code block. A do...while checks the condition after. That means the block always executes at least one time, even if the condition starts out false.
When does that matter? Think of a login form. You always want to show the form at least once — you check if the login was successful after the user submits it, not before they've even seen it. Or think of a game's main menu: show it first, then decide whether to keep showing it based on what the player picks.
In practice, do...while is genuinely rare in modern JavaScript. You'll mostly see it in interview questions and legacy code. But understanding it deepens your grasp of how loop conditions work, which makes you sharper with all the other loops too.
Production note: Because the loop body always runs once, do...while is useful for initialization logic that must execute before the condition check. For example, sending an initial request and then deciding whether to retry based on the response.
The for...in Loop — When to Use and When to Avoid It
JavaScript also provides a for...in loop, but it's designed for iterating over object keys, not arrays. It loops through all enumerable properties of an object, including inherited ones from the prototype chain. This makes it unpredictable for arrays because it returns keys as strings and includes array methods if any have been added to Array.prototype.
The rule of thumb: Never use for...in to iterate arrays. Use it only for plain objects when you need to loop over property names. For arrays, stick with for, for...of, or forEach.
Why it's dangerous for arrays: The iteration order is not guaranteed to be numeric index order. If you or a library has extended Array.prototype, those methods will appear as keys. This leads to subtle bugs that are hard to track down.
for...in on an array that had a polyfilled Array.prototype.includes. The loop iterated 'includes' as a key, causing the app to crash.for...of or forEach for arrays.for...in for objects, guard with hasOwnProperty.for...in only for iterating object keys, not arrays.hasOwnProperty to skip prototype properties.for...of or forEach for array iteration.The Infinite Loop That Brought Down the Dashboard
count < items.length was always true because count never increased. The loop ran indefinitely, blocking the event loop in Node.js (single-threaded).count++ inside the while loop. Also added a safety break: if (count > 10000) break; to guard against future logic errors. Implemented a maximum iteration guard in the code review checklist.- Always ensure the condition variable changes inside a while loop.
- Add a fail-safe iteration cap (e.g.,
if (iterations++ > MAX_SAFE) break;) for any unbounded loop. - Monitor event loop lag — it's the first signal of a blocked loop in production.
undefined when iterating<= instead of <? Check if index goes up to array.length - 1. Log the index and value at each iteration.break or continue. If you need early exit, switch to for or for...of. Also ensure the array is not null or undefined.console.log('loop iteration ' + i) to trace loop progression. If the log stops, the condition never turned false. Add an iteration counter with a max limit as a safety net.if (i > 10000) break; above the loop body.Key takeaways
Common mistakes to avoid
4 patternsOff-by-one error with array indexes
array[array.length] returns undefined. The last element is never processed, or the loop tries one too many.< array.length instead of <= array.length in the loop condition. Remember: arrays are zero-indexed, valid indices are 0 to length-1.Infinite loop due to missing variable update in while/do...while
Using `return` or `break` inside forEach expecting early exit
break causes a SyntaxError; return exits only the callback, not the loop.for loop or for...of if you need early exit. forEach is designed for processing all items; use it only when you intend to handle every element.Using for...in on arrays
for...of, forEach, or a classic for loop for arrays. Reserve for...in for plain objects, and add hasOwnProperty check.Interview Questions on This Topic
What is the difference between for...in and for...of in JavaScript, and why should you avoid for...in when iterating arrays?
Frequently Asked Questions
That's JS Basics. Mark it forged?
5 min read · try the examples if you haven't