Strange behaviour with JS; Can someone explain this output? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Strange behaviour with JS; Can someone explain this output?

I'm studying Node.js and recently found that bit OR operator(|) can cause strange behaviour. ~~~~~~~~~~ > 9 | 0 9 > 99 | 0 99 ... > 999999999 | 0 999999999 > 9999999999 | 0 1410065407 > 99999999999 | 0 1215752191 ~~~~~~~~~~ (tested on Node.js v12.18.2) Can someone explain this behaviour? P.S. Now I noticed that with many more digits the output is always zero. ~~~~~~~~~~ > 9999999999999999999999999 | 0 -2147483648 > 99999999999999999999999999 | 0 0 > 999999999999999999999999999 | 0 0 > 9999999999999999999999999999 | 0 0 ~~~~~~~~~~ Why? I'm confused by this. What is the exact behaviour of bit OR operator in Node.js?

20th Jul 2020, 8:19 PM
Kogia-sima
Kogia-sima - avatar
1 Answer
+ 4
when working with bitwise/shift operators in javascript, 32bit signed integers are used, so the largest safe number you can use is 2^(31)-1 or 2147483647. Otherwise it overflows.
20th Jul 2020, 9:15 PM
JME