Using JavaScript Logical Operators in ColdFusion 8
by Simon. Average Reading Time: about a minute.
Following on from my posts on Arithmetic and Assignment operators, Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
The logical operators are described in the following table:
| Operator | Usage | Description |
|---|---|---|
Logical AND (&&) |
expr1 && expr2 |
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false. |
Logical OR (||) |
expr1 || expr2 |
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false. |
Logical NOT (!) |
!expr |
Returns false if its single operand can be converted to true; otherwise, returns true. |
Using ColdFusion, the Logical operators can be expressed as follows:
Logical AND
In the below example, both operands, x and y, return true, therefore myVariable is set to true within the logical statement.
<cfscript> x = 9; y = 2; myVariable = false; if (x < 10 && y > 1) { myVariable = true; } </cfscript>

Logical OR
In the below example, neither x equals 10 nor y equals 1, therefore the first part of the logical statement is not resolved. Instead, the else statement is processed, assigning the boolean value false to the variable myVariable.
<cfscript> x = 9; y = 2; if (x == 10 || y == 1) { myVariable = true; } else { myVariable = false; } </cfscript>

Logical NOT
In the below example, x does not equal y. Ordinarily this would result in the logical statement being evaluated, however, a logical negation has been applied to the beginning of the expression to be evaluated, therefore the variable myVariable is assigned the boolean value true.
<cfscript> x = 9; y = 2; myVariable = false; if (!x==y) { myVariable = true; } </cfscript>

