Software Sue

Link to Simply Sue
Link to Sustainability Sue
location: software/scripting/javascript/logical operators Skip navigation : Home  

JavaScript Logical Operators


Although logical operators are usually used with Boolean (logical) values and return Boolean values, the && and || operators can be used with non-Boolean values, in which case they may return a non-Boolean value. <

Expressions that can be converted to false include those that evaluate to null, 0, the empty string (""), or undefined.

&& - Logical AND - returns its first operand if it can be converted to false. Otherwise, it returns the second operand.
|| - Logical OR - returns its first operand if it can be converted to true. Otherwise, it returns the second operand.
! - Logical NOT - returns false if its single operand can be converted to true. Otherwise, returns true. So, !true returns false, !false returns true, and !"Gog" returns false.

a b Logical AND: a && b returns: Logical OR: a || b returns:
true true true true
true false false true
false true false true
false (2==5) false false
"Gog" "Magog" Magog Gog
false "Magog" false Magog
"Gog" false false Gog

Short cuts:
false && anything always returns false,
true || anything always returns true.
When short cuts are used, the anything part is not evaluated, so there are no side effects from doing so.