skip to Main Content
function recursion(x) {
  if (x < 0) return
  console.log(x)
  recursion(x - 1)
}
recursion(5);

I am getting the following output
5
4
3
2
1
0 => i want to know why 0, isn’t the condition will be false at this point

3

Answers


  1. You have a wrong condition in the if, fix:

    function recursion(x) {
    if (x < 1) return
      console.log(x)
     recursion(x-1)
    }
    recursion(5);
    Login or Signup to reply.
  2. The condition you putted that is if(x = 5 < 0) that means it will iterates untill the "x" value is not less then "0". so according to your condition it takes to the 0 .
    I hopes you find the answer.

    Login or Signup to reply.
  3. There are a few ways to fix this:

    • less-than-or-equals (<=) 0, or
    • less-than (<) 1
    function recursion(x) {
      if (x <= 0) return; // base case
      console.log(x);
      recursion(x - 1);
    }
    recursion(5);

    Here is the iterative version:

    function iteratation(x) {
      while (x > 0) {
        console.log(x--);
        // Alternatively, two separate statements:
        // >> console.log(x);
        // >> x--;
      }
    }
    iteratation(5);

    Could also be written as:

    function iteratation(x) {
      for (let i = x; x > 0; x--) {
        console.log(x);
      }
    }
    iteratation(5);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search