Why (x ^ 0 === x) prints x instead of true / false?

I did the exercise when testing if the variable is an integer. x ^ 0 === xwas one of the suggested solutions, however, when I try to do this in the Chrome 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);
Run code
+4
source share
3 answers

Your condition was mistakenly evaluated due to the fact that you missed adding ()around x^0:

function isInteger(x) {
  console.log((x ^ 0) === x);
}

isInteger(5);
isInteger(124.124)
isInteger(0);
Run code
+5
source

While the messerbill answer explains the problem, there is one more. This is not a good way:

function isInteger(x) {
  console.log((x ^ 0) === x);
}

isInteger(281474976710656);
Run code

The reason is that bitwise operators force operands up to 32 bits. Better use this:

function isInteger(x) {
  console.log((x % 1) === 0);
}

isInteger(5);
isInteger(124.124)
isInteger(0);
isInteger(281474976710656);
Run code
+3

In addition to the answers provided, the concept associated with the problem is the “ operator priority ”. This page is where I go when I have similar problems in JS (different languages ​​may have slightly different operator priorities, for example, the exponent operator **in js and php ).

So, from the examples in the answers:

(x ^ 0) === x

brackets required

and

x % 1 === 0

no.

0
source

Source: https://habr.com/ru/post/1694305/


All Articles