Those are not logical operators but bitwise operators. In weakly-typed languages where 1 is coerced to true and 0 to false they are mostly equivalent, but lack short-circuit behaviour. As such, they will perform worse in some situations and should not be used where a logical operator is intended.
In languages where the logical operators yield the terminating value, they will also result in a different return value in most cases:
Code:
// Javascript
true && false // false
true & false // 0
({}) || undefined // ({}) (only the first operand matters because the result would be the same no matter the second; the object is the terminating value, and is returned)
({}) | undefined // 0 (the object is coerced to 1, and undefined to 0)
function foo() {
return true;
}
function bar() {
return false;
}
bar() && foo() // false; only bar is called
bar() & foo() // 0; both bar and foo are called
In strongly-typed languages, using a bitwise operator on boolean values will yield an error:
Code:
-- Haskell
import Data.Bits
1 .&. 2 :: Int -- 0
True .&. False :: Int
-- Couldn't match expected type `Int' against inferred type `Bool'
-- In the expression: True .&. False :: Int
Bookmarks