Randomblue
Randomblue

Reputation: 116283

Bitwise operations on non numbers

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?

Upvotes: 16

Views: 1529

Answers (2)

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

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:

  1. Let number be the result of calling ToNumber on the input argument.
  2. If number is NaN, +0, -0, +Inf, or -Inf, return +0.

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227240

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

Upvotes: 14

Related Questions