Somehow, JavaScript makes sense of the bitwise operations NaN ^ 1, Infinity ^ 1 and even 'a' ^ 1 (all evaluate to 1).
What are the rules governing bitwise operators on non numbers? Why do all the examples above evaluate to 1?
Somehow, JavaScript makes sense of the bitwise operations NaN ^ 1, Infinity ^ 1 and even 'a' ^ 1 (all evaluate to 1).
What are the rules governing bitwise operators on non numbers? Why do all the examples above evaluate to 1?
According to the ES5 spec, when doing bitwise operations, all operands are converted to ToInt32 (which first calls ToNumber. If the value is NaN or Infinity, it's converted to 0).
Thus: NaN ^ 1 => 0 XOR 1 => 1
ECMA-262 defines in 11.10 that arguments of binary bitwise operators are converted with ToInt32. And 9.5 that explains ToInt32 says in its first two points:
- Let number be the result of calling ToNumber on the input argument.
- If number is NaN, +0, -0, +Inf, or -Inf, return +0.