Logical Operators

The bitwise operators are all useful in their place, but far more often you just want a simple Boolean and or or operator that converts its operands to Boolean values rather than integers.

These operators (called logical operators to distinguish them from the bitwise operators) also perform short-circuit evaluation. This means that they evaluate their left operand first, and if that is enough to tell the final result, the right operand isn’t evaluated.

Logical and is represented by && . It evaluates its left operand first: if this converts to Boolean false, the result of the operation is false. If the left operand can’t be converted to a Boolean, the result of the operation is invalid. In both cases, the right operand isn’t evaluated at all. If, however, the left operand converts to Boolean true, the result of the operation is the right operand, converted to a Boolean value.

Logical or is represented by || . It evaluates its left operand first. If this converts to Boolean true, the result of the operation is also true. Just like logical and, if the left operand can’t be converted, the result of the operation is invalid. Also like the logical and operation, in both cases the right operand isn’t evaluated at all. If the left operand converts to Boolean false, however, the result of the operation is the right operand, also converted to a Boolean value.

For example:

(1+1 == 2) || foo( ) gives true, with no call to foo( )
(1+1 == 3) || foo( ) gives the result of foo( ...

Get Learning WML, and WMLScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.