Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript bitwise undefined pitfalls?

What is the logic of bitwise operators on undefined???

var x;
console.log(x);     // undefined
console.log(x^7);   // 7
console.log(7^x);   // 7
console.log(x|7);   // 7
console.log(7|x);   // 7
console.log(7&x);   // 0
console.log(x&7);   // 0
console.log(~x);    // -1
console.log(x*2);   // NaN
console.log(x/2);   // NaN
console.log(x+2);   // NaN
console.log(x-2);   // NaN

I can see some sense in NaN. Because undefined -2 is really 'not a number'. But I do not follow any logic on bitwise operators and undefined.

like image 697
CoR Avatar asked May 04 '13 00:05

CoR


1 Answers

The internal function [ToInt32] is called on all operands for all bitwise operators.

Note that ToInt32(undefined) -> 0 and the range is [0, 2^32)

like image 57
user2246674 Avatar answered Sep 28 '22 05:09

user2246674