# 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:

 Operator Description && 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:

• false becomes 0

• true becomes 1

• 0 becomes false

• Any non-zero value becomes true

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:

• This is not to be confused with the bitwise operators, which yield a 32-bit integer value instead of the Boolean value yielded by a logical expression.

• The bitwise operators may yield a value that in other languages is the same as the logical operator. However although in C language, true and false are really integer values, in JavaScript the Boolean and Number values are distinctly different types.

• Be careful to use the correct number of ampersands, and vertical bars to select the logical version of the operator. Refer to the Bitwise operator topic for a list of operators to avoid in logical expressions.

## Cross-references:

ECMA 262 edition 2 - section - 11.11

ECMA 262 edition 3 - section - 11.11

Wrox Instant JavaScript - page - 19