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.
CodePudding user response:
!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.
CodePudding user response:
First
var n = x / 2
n
will be falsey if x is 0, and truthy otherwise.
If the argument is even and not 0:
- m will be 0
- n will be a truthy number (because anything divided by 2 is another non-zero number - except 0)
- !n will be false (because that's the boolean inverse of 0, a falsey value)
- the return statement is 0 <= false; false gets converted into a number when compared with <=, and 0 <= 0 is true
If the argument is odd and positive:
- m will be 1
- n will be truthy (because any odd number divided by 2 is another non-zero number, and a non-zero number is truthy)
- !n will be false (because that's the boolean inverse of a truthy value)
- the return statement is 1 <= false; false gets converted into a number when compared with <=, and 1 <= 0 is false
If the argument is even and 0:
- m will be 0
- n will be 0
- !n will be true (boolean inverse of 0)
- the return statement is 0 <= true; true gets converted into a number when compared with <=, and 0 <= 1 is true
But the code doesn't work when the argument is odd and negative, because a negative odd number % 2
gives -1, not 1.
- m will be -1
- n will be truthy (because any odd number divided by 2 is another non-zero number, and a non-zero number is truthy)
- !n will be false (because that's the boolean inverse of a truthy value)
- the return statement is -1 <= false; false gets converted into a number when compared with <=, and -1 <= 0 is true - when it should be false