Reputation: 2133
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:
Upvotes: 2
Views: 352
Reputation: 632
The function you provided will recursively call itself until num is 0, and then the results will bubble back up.
So:
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
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
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