DEV Community

Discussion on: Recursion Revealed

Collapse
 
thorx86 profile image
Athaariq Ardhiansyah

Beware of stack overflow error (no, it's not a site, it is an error). So the recursion really good at small repetition. However, it might overwhelm the computer if too much repetition, can ended up program to crash.

The solution? Use while loop

Before:

function decrement(n) {
    if(n > 0) {
        return decrement(n-1);
    } else {
        return n;
    }
}
console.log(decrement(10));
Enter fullscreen mode Exit fullscreen mode

After:

function decrement(n) {
    while(n > 10) {
        n -= 1; // This can be n--, actually
    }
    return n;
}
console.log(decrement(10));
Enter fullscreen mode Exit fullscreen mode

Thanks!