Whilst reading Javascript Allonge I got stuck trying to figure out why this;
((n) => {
const even = (x) => {
if (x === 0)
return true;
else
return !even(x - 1);
}
return even(n)
})(97)
returns true of false depending on the number supplied being odd or even.
When I look at it I think it is checking if the number supplied is 0 and if not subtracting 1 then checking again. This would mean the number eventually reached 0 and returns true. This is obviously NOT what is happening as for 97 it returns false and 96 true.
The only thing I don't know here is the bang before even in return !even(x -1);.
Oh, this is terrible, in a wonderful kind of way. What a way to write code to check for odd and even numbers!
The first thing to note is that this is a recursive function: it calls itself repeatedly. Each time, it decrements the number concerned, so it eventually gets all the way down to 0.
The "clever" thing that this code does is the !, which inverts the boolean result of the function call. true becomes false and false becomes true. You can do this repeatedly: !!true is true and !!!true is false.
Essentially, this code can be reduced to something like the following:
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!true;
If there are an even number of ! negations, we end up with true. If there are an odd number, we end up with false.
The code you cite adds n ! logical NOT operators to true, where n is the value that we're testing. An odd number of !s results in false; an even number results in true.
This is clever code: it is not good code to use in production! It's somewhere in the region of 1200 times slower than the simple % 2 test.
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