JavaScript loop exercises
A loop that runs one step too far in JavaScript does not crash: it reads undefined and carries on, and the wrong value shows up somewhere else. These exercises are short loops with one bug each, from bounds and stop conditions to closures and async.
Infinite loops are stopped safely after a few seconds, so experiment freely.
The loops bugs you will meet
- i <= arr.length reads one past the end and gets undefined.
- A while loop that never changes its condition never ends.
- var in a loop is shared by every callback; let gives each pass its own.
- forEach does not wait for async callbacks.
- Adding to a total declared inside the loop resets it every pass.
The exercises
Easy
Medium
- Finding the first negative number crashesScope and closure
- Score total turns into NaNNull and undefined
- Reversing a word never finishesInfinite loops
- Vote total shows "034" instead of 7Type
- Total shows "[object Promise]" instead of 6Async and race conditions
- Grouping words keeps only one per groupLogic
- Counting odd numbers freezes on an even oneInfinite loops
- Counting capitals freezes on a lowercase letterInfinite loops
- Joining words leaves a dash at the endOff-by-one
- AI Attempt: Remove all occurrencesLogic
Hard
- Removing duplicates never finishesInfinite loops
- Every callback reports index 3Scope and closure
- Cached loader runs 3 times instead of onceAsync and race conditions
- 3 people book the last seatAsync and race conditions
- Search freezes when the value is missingInfinite loops
- Two identical records counted as differentType
Errors you might be searching for
More JavaScript practice by topic
Questions
What if my fix loops forever?
The test is stopped after a few seconds and marked as timed out, and the page keeps working.
Can I step through the loop?
Yes. After a run, the line-by-line view shows each variable on every pass.