techie_28
techie_28

Reputation: 2133

Final Value of a Variable in a JavaScript Recursive Function call

    function even(num) {//console.log(num) => shows 1 & then 0 before terminating.
            if (num === 0) {
                return true;
            } else {
                return !even(num - 1);
            }
        }
    console.log(even(1));
//Why Chrome Console shows num = 1 when .log is being executed.

The Else part of the recursive function even would run till num becomes 0 this is quite clear but the chrome developer console shows num = 1 print when console.log is logging

Is the final value going to be 0 or 1?

Screenshot after the calls are completed:

enter image description here

Upvotes: 2

Views: 352

Answers (3)

Owen Campbell
Owen Campbell

Reputation: 632

The function you provided will recursively call itself until num is 0, and then the results will bubble back up.

So:

  1. even( 1 ) is called - current function: even( 1 )
  2. even( 0 ) is called by even( 1 ) - current function: even( 0 )
  3. even( 0 ) returns true back to even( 1 ) - current function: even( 1 )
  4. even( 1 ) returns !true: false - current function: main, but even( 1 ) was the last function called.

At the end, the last version of even() the code was running in was even( 1 ). The debugger will show num = 1 because that was the last value num had before returning.

To see this in action:

function even(num) {
  console.log( "num is: " + num + " before function" );
  if (num === 0) {
    return true;
  } else {
    var returnValue = !even(num - 1);
    console.log( "num is: " + num + " after recursion" );
    return returnValue;
  }
}
console.log(even(5));

Upvotes: 1

Pankaj Bisht
Pankaj Bisht

Reputation: 994

Yes chrome showing right when we use that kind of data structure like recursion then here what happen all call going to stack and all operation happening according to stack push and pop operation. So

when you pass 1 to function then basically what is happening the value of num is -

1 -> 0 in stack but when your condition is true now stack is releasing so it will back on original state and the last value is 1 so that why you are getting 1.

Upvotes: 1

Miguel Angel
Miguel Angel

Reputation: 983

The response will be false for odd numbers, and true for even. That looks pretty exactly what you need. But this looks overcomplex, why don't do just

function even(num) {
    return n % 2 == 0;
}

Upvotes: 1

Related Questions