There are three conversions to study. Obviously Boolean values will remain as they are.
This table summarizes the effects of converting values to Boolean:
Value: | Boolean equivalent: |
---|---|
null | false |
Undefined value | false |
Non empty string | true |
Empty string | false |
0 | false |
NaN | false |
Infinity | true |
Negative infinity | true |
Any other non zero number | true |
Object | true |
Array | No direct boolean equivalent |
Function | true |
There is no proper Boolean equivalent for an array. The ECMA standard does not address this either. The standard does suggest that any non-null object reference convert to true and since an array is an object, it should rightly become a true value.
Some non-portable behavior has been implemented in the MSIE and Netscape browsers. In some cases, the array becomes true in all cases. In others, a non-empty array is true, while an empty array is false. This seems to be based on the length value.
You should test your target browsers to see what behavior persists if you intend to use this capability and not rely on any implicit array conversion facilities. It is probably safest to implement your own conversion method.
The array to Boolean conversion is so inconsistently supported as to render it unusable in any cross-browser implementation.
A more insidious side effect is exhibited by the fact that all objects convert to the Boolean true value, even a Boolean object whose value is false. This is demonstrated in the example. You really need to be careful if you are storing Boolean values in objects rather than simple variables, especially if they are driving some conditional code execution.
<!-- Is this a bug or a feature??? --> <HTML> <HEAD></HEAD> <BODY> <SCRIPT> myTrueObject = new Boolean(false); if(myTrueObject) { alert("True"); } else { alert("False"); } </SCRIPT> </BODY> </HTML>
Prev | Home | Next |
Conversion | Up | Conversion to a number |
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. |