Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 873
THE JOATMON Avatar asked Jan 29 '23 13:01

THE JOATMON


2 Answers

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);
like image 118
messerbill Avatar answered Jan 31 '23 08:01

messerbill


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);
like image 35
Patrick Roberts Avatar answered Jan 31 '23 07:01

Patrick Roberts