Availability: |
| ||||||||
Property/method value type: | Boolean primitive | ||||||||
JavaScript syntax: | - | anOperand1 || anOperand2 | |||||||
Argument list: | anOperand1 | A Boolean value | |||||||
anOperand2 | Another Boolean value |
Traditionally in programming environments, the logical OR operator yields true when either or both of the operands are true. It yields false only when both are false. However, the specifics of this are slightly different in JavaScript and although the results may appear to be functionally the same, there is a subtle but important difference.
First, lets deal with the normal and expected behavior of a Logical OR operator. The truth table shows the result of this operator for two Boolean primitive values:
Now, the implementation is expected to conform to the ECMA standard. This sets out the following method of evaluation for a Logical OR operator:
Evaluate and convert the first operand using the ToBoolean() method.
If it is true, then return that operand.
Otherwise evaluate and return the second operand.
To all intents and purposes the external perceived behavior is the same because another ToBoolean() conversion is likely to take place in the context that the expression is used - an if() statement or an outer logical expression for example.
The associativity is from left to right.
Refer to the operator precedence topic for details of execution order.
<HTML> <HEAD></HEAD> <BODY> <TABLE BORDER=1 CELLPADDING=2> <TR> <TH>A</TH> <TH>B</TH> <TH>OR</TH> </TR> <SCRIPT> for(a=0; a<2; a++) { for(b=0; b<2; b++) { document.write("<TR ALIGN=CENTER><TD>"); document.write(Boolean(a)); document.write("</TD><TD>"); document.write(Boolean(b)); document.write("</TD><TD>"); document.write(Boolean(a || b)); document.write("</TD></TR>"); } } </SCRIPT> </TABLE> </BODY> </HTML>
Prev | Home | Next |
Logical operator | Up | Logical XOR |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |