I can't figure out how this recursive call works. Using the not operator in the recursive call somehow makes this function determine if the argument given is odd or even. When the '!' is left out fn(2) and fn(5) both return true.
This example is taken out of JavaScript Allonge free e-book, which, so far has been excellent.
var fn = function even(n) {
if (n === 0) {
return true;
}
else return !even(n - 1);
}
fn(2); //=> true
fn(5); //=> false
So, here, the first recursive call takes place. If it returns a logical true, nothing further happens, otherwise the second recursive call takes place, then. What the || operator does here is exactly the same thing it does in any other expression.
A recursive function terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case. A base case is a case, where the problem can be solved without further recursion. A recursion can end up in an infinite loop, if the base case is not met in the calls.
Simple examples of a recursive function include the factorial, where an integer is multiplied by itself while being incrementally lowered. Many other self-referencing functions in a loop could be called recursive functions, for example, where n = n + 1 given an operating range.
n === 0
the result is true
.n > 0
it returns the inverse of n - 1
.n === 1
it will return !even(0)
, or false
.n === 2
it will return !even(1)
, or !!even(0)
, or true
.n === 3
it will return !even(2)
, or !!even(1)
, or !!!even(0)
, or false
.In general:
n
is even, the result is inverted an even number number of times, meaning it will return true
. n
is odd, the result is inverted an odd number number of times, meaning it will return false
.The above function reurns recursively the negation of it self.The base-case is when the number provided becomes zero and each time the function calls it self the number is decreased by one. As a result we have n recursive negations starting with true at base-case (where n is the number provided). For an odd number of negations given true as a starting value you get false as the result and for an even number you get true. In summary:
Lets say we have example n=5
recursive reduction of n. Values of n at each level:
5
4
3
2
1
0 (base-case)
returned values at each level:
true (base case)
!true
!!true
!!!true
!!!!true
!!!!!true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With