Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Can someone explain why the JavaScript example equals 2?



The JS code in question:

console.log([1,2,3,4,5,6,7] ^ 2);

This produces 2 because ^ is the bitwise XOR operator in Javascript. Arrays are not numeric types, so they appear to be coerced to 0 for this comparison. In short, they are effectively logging "0 XOR 2", which is 2.


I think it is actually NaN since it should be equivalent to Number([1,2,3])


^ is XOR. The author’s “translation” to JavaScript made inconsistent changes in the notation. Here we’re XOR between 2 and a non numeric value, which is coerced into a Number (NaN I think here), and NaN bitshifted with anything gives that thing.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: