View Full Version : & vs. && - Does it matter?
peterinwa
06-18-2003, 05:10 AM
if (a==b && d==d){whatever}
I learned to use && but noticed that I have done much coding (by accident) with only a single & and it's never caused a problem.
Does it mater?
Thanks, Peter
beetle
06-18-2003, 05:46 AM
The single ampersand is the bitwise AND, whereas the double ampersand is the logical AND.
After some tests - it seems the bitwise operator returns a 1 where you'd expect TRUE from the logical operator, and 0 where you'd expect FALSE from the logical operator. As we all (should) know - 1 evaluates to TRUE in a condition, and 0 evaluates to FALSE. Here's why:
Let's take this logical condition
2 == '2'
This will return true. Since & is a bitwise operator, TRUE in binary is a 1. Now
2 === '2'
This will return false. Again - false in binary is 0. So, if we take this compound condition
if ( 2 == '2' & 2 === '2' )
and reduce the equality comparisons into their binary result
if ( 1 & 0 )
If you understand bitwise operations (learn here (http://msdn.microsoft.com/library/en-us/script56/html/js56jsoprbitwiseand.asp?frame=true)) then you'll know that 1 & 0 returns a 0.
Now we're back to our logical condition. Since a 0 evaluates as FALSE, our condition fails as we'd expect.
Of course, had we used the logical operator from the start
if ( 2 == '2' && 2 === '2' )
All this boolean-to-binary switching wouldn't have to take place.
So, although you get the correct result - you are making improper use of the operator, and bitwise operations are more costly to perform in a logical setting.
Did I just make any sense? :p
Using & is fine for most cases. As beetle said, true casts to 1 and false typecasts to 0, making & behave identically as && for boolean conditions.
However, there is an important difference.
&& short-circuits, & doesn't.
Example:
var a = 0, b = false;
var anded = b && a++;
alert(a) // 0;
var c = 0, d = false;
var anded2 = d & c++;
alert(c); // 1
beetle
06-18-2003, 06:40 AM
thanks jkd - that's good to know. Not sure I'll ever need it, but good to know.
I thought of an instance where it could bite you in the but. Let's assume this function
function add( num1, num2 )
{
if ( num1 & num2 )
{
return num1 + num2;
}
alert( "You must include two numbers" );
return null;
}
var sum = add( 1, 2 );
Okay, so it's not the best example, and probably a REMOTE possibility (since you should be using typeof here) but it crossed my mind.
peterinwa
06-18-2003, 07:27 AM
Thanks. Sounds like & will be fine for my simple if statements but I'll keep my eye on it.
Peter
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.