16

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?

Paul
  • 139,544
  • 27
  • 275
  • 264
Randomblue
  • 112,777
  • 145
  • 353
  • 547

2 Answers2

14

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

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • 1
    Those spec..... +1 And I thought it's `function bitwise(obj){ if (typeof o !== "Number") return 1; }` – gdoron Jun 14 '12 at 17:00
  • @gdoron: Gotta love the spec :-P – gen_Eric Jun 14 '12 at 17:03
  • 1
    If they'll give me your rep, I'll. `:)` Just worth mentioning that the result depends of the second operand. Example: `"A" ^ 2 === 2 // true` – gdoron Jun 14 '12 at 17:04
  • 1
    For the sake of completeness, any *non-number literal string* is **`NaN`** then `"a" ^ 1 = 1` – Alexander Jun 14 '12 at 17:05
  • @Alexander. Almost, any non number (all other types like objects and arrays) evaluated to NaN. `/fndsjkn/ ^ 1 == 1` – gdoron Jun 14 '12 at 17:07
3

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.
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68