skip to Main Content

Here is the recursion code.

function factorial(n) {
    if (n === 0 || n === 1) {
        return 1;
    } else {
        console.log(factorial( (n - 1) ));
        return n * factorial(n - 1);
    }
}

const number = 5;
const result = factorial(number);
console.log(result);`
Output:
1
2
1
6
1
2
1
24
1
2
1
6
1
2
1
120

#Why does the output include repeated ‘1’ and ‘2’ values?

#How does the recursive function behave in this scenario, and why does it produce this specific output?

#Is this behavior related to how recursion works in JavaScript?

3

Answers


  1. Your log prints another recursion, instead of printing the current step

    function factorial(n) {
        console.log('current value:', n);
        if (n === 0 || n === 1) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
    
    const number = 5;
    const result = factorial(number);
    console.log("result:", result);
    Login or Signup to reply.
  2. Just Remove console.log from the recursive function.

    New Code

    function factorial(n) {
        if (n === 0 || n === 1) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
    
    const number = 5;
    const result = factorial(number);
    console.log(result);
    
    Login or Signup to reply.
  3. function countdown(n) {
      if (n <= 0) {
        console.log("Blastoff!");
      } else {
        console.log(n);
        countdown(n - 1);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search