Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a & logical operator in Javascript

Tags:

javascript

I was wondering if there is a "&" logical operator in Javascript. I tried running 1 & 0 and 1 && 0 in Firebug(Firefox) and it returned a 0 for both.

Someone told me that C# accepts both & and double &&, double being more efficient as it will exit the comparison loop as soon as a false is encountered, but I was not able to find any info for Javascript on that.

Any ideas?

like image 978
DLS Avatar asked Jul 30 '10 19:07

DLS


3 Answers

No. & is a bitwise AND operator. && is the only logical AND operator in Javascript.

like image 79
Josh Stodola Avatar answered Oct 12 '22 09:10

Josh Stodola


The && operator returns 0 for the expression 1 && 0 because its semantics are different than those of the same operator (well, symbolically the same) in other C-like languages.

In Javascript, the && operator does coerce its operands to boolean values, but only for the purposes of evaluation. The result of an expression of the form

e1 && e2 && e3 ...

is the actual value of the first subexpression en whose coerced boolean value is false. If they're all true when coerced to boolean, then the result is the actual value of the last en. Similarly, the || operator interprets an expression like this:

e1 || e2 || e3 ...

by returning the actual value of the first en whose coerced boolean value is true. If they're all false, then the value is the actual value of the last one.

Implicit in those descriptions is the fact that both && and || stop evaluating the subexpressions as soon as their conditions for completion are met.

like image 34
Pointy Avatar answered Oct 12 '22 09:10

Pointy


1 & 0 is 0.

It's a bitwise operator, not a logical operator.

&& means a logical AND of the left and right operators. This means it will return a boolean true value only if both the left and right operators resolve to boolean true.

& means a bitwise AND of the left and right operators. This means the bits of each operand will be compared and the result will be the ANDed value, not a boolean. If you do 101 & 100 the return value is 100. If you do 1 & 0, the return value is 0.

You've been mislead about the meaning of the two operators if someone told you the difference was just in efficiency. They have very different uses.

like image 36
Jonathon Faust Avatar answered Oct 12 '22 08:10

Jonathon Faust