I was doing an exercise on testing if a variable is an integer. x ^ 0 === x
was one of the proposed solutions, however when I try that in Chrome's console, on codepen.io or here, it returns x
. Why is this?
function isInteger(x) {
console.log(x ^ 0 === x);
}
isInteger(5);
isInteger(124.124)
isInteger(0);
Your condition is evaluated wrongly due to you missed to add ()
around x^0
:
function isInteger(x) {
console.log((x ^ 0) === x);
}
isInteger(5);
isInteger(124.124)
isInteger(0);
While messerbill's answer explains the problem, there is another one. This is not a good method to use:
function isInteger(x) {
console.log((x ^ 0) === x);
}
isInteger(281474976710656);
The reason why is because bitwise operators coerce the operands to 32 bits. Better to use this:
function isInteger(x) {
console.log((x % 1) === 0);
}
isInteger(5);
isInteger(124.124)
isInteger(0);
isInteger(281474976710656);
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