I was playing around with on of the excercises when I coded this:
function isEven(x){
var m = x % 2
var n = x / 2
return m <= !n
}
The funny part is that it actually works, but I do not understand if !n makes the number negative or affects the boolean value itself. Can someone explain how my code works? Thanks.
!n is a red herring. For any value of x other than 0, !n will be false; it will be true when x == 0.
m is 0 for even numbers, 1 for odd numbers. When you compare a number with a boolean, the boolean is converted to a number. So m <= false is equivalent to m <= 0. This will be true when m is 0.
So you can get rid of n and just use this:
function isEven(x){
var m = x % 2;
return m <= false
}
[0, 1, 2, 3, 4, 5, 6, 7, 8].forEach(x => console.log(x, isEven(x)));
The reason why it works with !n is because in the only case where !n is true, x == 0 and m == 0. 0 <= true is true, so the function returns the correct result then as well.
First
var n = x / 2
n will be falsey if x is 0, and truthy otherwise.
If the argument is even and not 0:
If the argument is odd and positive:
If the argument is even and 0:
But the code doesn't work when the argument is odd and negative, because a negative odd number % 2 gives -1, not 1.