Logical operator (Definition)

An operator that creates a logical (Boolean) expression.

Availability:

ECMAScript edition - 2
Property/method value type:Boolean primitive

Logical operators perform a one bit operation on the Boolean value of the operands. The input values may not be Boolean values but will be converted to a Boolean value using the toBoolean rules for that type. The conversion happens automatically but may not always be what you expect.

The JavaScript interpreter is also quite smart, in that it can for some operator and value combinations perform a lazy evaluation. For example if an expression like this is presented:

A AND B

Then if A is false, B does not need to be evaluated to know that the result will be false. This can significantly speed up the interpreter because evaluating B might have involved an object reference or perhaps an expression evaluation. It almost always would involve a type conversion from some other type to a Boolean value. This suggests you may effect some performance gains by coding your logical operations to take advantage of this.

There are specific logical operators in the set for performing logical AND as well as logical OR operations. However, generally speaking any operator that yields a Boolean result could be used in the same place. The following table summarizes the logical operators as well as those, which come under that general heading of providing a Boolean result:

OperatorDescription
&&Logical AND
||Logical OR
!Logical NOT
==Equal to
!=NOT equal to
<Less than
<=Less than or equal to
>Greater than
>=Greater than or equal to

The Boolean constants true and false need to be considered too, because they are often used in conditional tests to force the conditions to be true or false. Although they are not operators as such, they can be useful when constructing expressions for debugging purposes.

Type conversions indicate these relationships:

Note that this is going to lose some information if you convert a non-zero value other than 1 to a Boolean value and back again.

Warnings:

See also:Associativity, Binary logical operator, Bitwise operator, Equal to (==), Expression, Greater than (>), Greater than or equal to (>=), Identically equal to (===), Less than (<), Less than or equal to (<=), Logical AND (&&), Logical NOT - complement (!), Logical OR (||), NOT Equal to (!=), NOT Identically equal to (!==), Operator, Operator Precedence, ToBoolean, Type, Type conversion

Cross-references:

ECMA 262 edition 2 - section - 11.11

ECMA 262 edition 3 - section - 11.11

Wrox Instant JavaScript - page - 19