A couple questions about recursion

I still have a couple questions after reading “What is Recursion? A Recursive Function Explained with JavaScript Code Examples” by Nathan Sebhastian

What is Recursion? A Recursive Function Explained with JavaScript Code Examples.

Under the section, “why don’t you just use a loop,” the only answers seemed to be if you were using a language like Closure, or you needed to use recursion for an interview question. Is this true? Are there not cases when recursion works better than a while/for loop?

Second question is a code sample from the same section which reads:

Blockquote

function randomUntilFive(result = 0, count = 0){
    if(result === 5){
        console.log(`The random result: ${result}`);
        console.log(`How many times random is executed: ${count}`);
        return;
    }
    result = Math.floor(Math.random() * (10 - 1 + 1) + 1);
    count++;
    randomUntilFive(result, count);
}

randomUntilFive();

Is there some reason to use “10 + 1 - 1” rather than just “10”?

Thank you.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.