This is driving me insane. Here is the code :
function laugh(){ let counter = 10; if(counter <= 0){ return; } else{ console.log('laugh'); counter--; laugh() } }
Why is this giving me an infinite loop when it’s supposed to print ‘laugh’ 10 times?
Advertisement
Answer
Like other answers said, each laugh()
created a new local counter.
The most appropriate recursive method here is to pass the counter as an argument:
function laugh(counter){ if(counter <= 0){ return; } else{ console.log('laugh'); laugh(counter - 1) // subtract 1 from the counter and recur } } laugh(10)
This is a pure function approach, reducing the reliance on global vars which can be affected by other functions. It’s generally a safer way to program than to use global variables when you don’t need to.