tags:

views:

165

answers:

4

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?

+1  A: 

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. :)

Tor Valamo
Breton
Evgeny
@Breton Actually I believe he is correct. You could use any strings and the result would be the same. Bitwise operators are for numeric values, not strings. Please revert your vote. Thanks, @Tor!
Josh Stodola
He edited his answer, and for some reason it doesn't mark it as edited. Oh well. Reverted.
Breton
Yeah I edited it... there's probably by design a short gap where edits aren't picked up. :)
Tor Valamo
Ooops, can't revert my vote unless the post has been edited. A bug in stack overflow?! never!
Breton
how 'bout now? :P
Tor Valamo
there we go! worked like a charm.
Breton
+1  A: 

& 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!

Evgeny
+1 on the Lack of error message. Should have been a syntax error, at least!
Josh Stodola
It's valid syntax, though.
harto
+14  A: 

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:

  1. Binary Bitwise Operators ECMA-262, 3rd. Ed. Section 11.10

  2. ToInt32, ECMA-262, Section 9.5

CMS
While I think @Tor tipped me off the quickest, I'll +1 you because you provided reference and and final expression.
Josh Stodola
Crescent Fresh
A: 

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"

Breton