I understand the first part of the if, but isn't the second part stating "since 'n' is not equal to zero, return 'n' in the even function modified with the logical NOT(!) operator."?
Doesn't that return 4 if I were to pass 5 as the argument to fn();?
var fn = function even (n)
{
if (n === 0)
{
return true;
}
else
{
return !even(n - 1)
}
};
fn(5); //=> false
even(n) is always the opposite of even(n-1).
As even(0) is true, even(1) is false and so on : all multiples of 2 give true and odd numbers give false.
A simple way to see it might be to log [0,1,2,3,4,5].map(even).
Just in case you were really looking for a way to know if a positive integer is even, the solution you show is very very inefficient and the recursion results in a call stack explosion for any big number. Here's a more reasonable solution :
function even(n){
return !(n%2);
}
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