I really think the title explains it thoroughly enough. I stumbled upon this oddity when I used an ampersand instead of a plus sign in some string manipulation code. Found it interesting. Could somebody explain this for me?
JavaScript, like many languages, has a bit operator & This compares the bits at similar positions and returns a 1-bit in those positions where they both have a 1-bit and a 0-bit in those positions where either one has a 0-bit.
And the important thing why it returns 0 is not because no bits match, but because it doesn't support strings. :)
& is the bitwise AND operator (as opposed to &&, which is the logical AND operator). A bitwise & makes no sense on strings, so I suppose JavaScript just takes the easy way out and returns 0.
There could be a more technical explanation, but basically you gave a nonsensical instruction and got back a nonsensical result. It would have been nicer to get an error, but JavaScript is just not that kind of language!
Because all bitwise operators1, including the bitwise and (&), work with 32-bit integers.
This operator will convert the two operands to signed 32-bit integers using the abstract ToInt32 operation 2, and if the value is not a number, the result of this conversion is 0.
At the end your expression becomes evaluated as:
0 & 0; // 0
References:
Binary Bitwise Operators ECMA-262, 3rd. Ed. Section 11.10
ToInt32, ECMA-262, Section 9.5
that's a bitwise & which is casting its arguments to be numbers. when you cast an arbitrary string to a number, and that string doesn't contain numerical text, then the result is NaN.
the result of NaN & NaN is 0 for some reason.
try "2" & "3"