What will this print?


function doSomething(iterations = 0) {
  if (iterations < 10) {
    console.log("Let's do this again!")
    doSomething(iterations++)    
  }
}
doSomething()

The answer is it will print

Let's do this again!
Let's do this again!
Let's do this again!
Let's do this again!
Let's do this again!
Let's do this again!
Let's do this again!
Let's do this again!
...forever...

The bug is the use of a "postfix increment" which is a bug I had in some production code (almost, it never shipped).

The solution is simple:


     console.log("Let's do this again!")
-    doSomething(iterations++)
+    doSomething(++iterations)    

That's called "prefix increment" which means it not only changes the variable but returns what the value became rather than what it was before increment.

The beautiful solution is actually the simplest solution:


     console.log("Let's do this again!")
-    doSomething(iterations++)
+    doSomething(iterations + 1)    

Now, you don't even mutate the value of the iterations variable but create a new one for the recursion call.

All in all, pretty simple mistake but it can easily happen. Particular if you feel inclined to look cool by using the spiffy ++ shorthand because it looks neater or something.

Comments

Your email will never ever be published.

Previous:
Create a large empty file for testing September 8, 2022 Linux
Next:
Find the largest node_modules directories with bash September 30, 2022 Linux, Bash, macOS
Related by category:
You don't need a context or state manager for TanStack Query in scattered React components January 2, 2026 JavaScript
gg2 has a web page now January 5, 2026 JavaScript
Always run biome migrate after upgrading biome August 16, 2025 JavaScript
Video to Screenshots app June 21, 2025 JavaScript
Related by keyword:
"Increment numbers in a string" October 20, 2005 Python