JavaScript 1.3 Overview, Part II: Changes to the Boolean Object - Doc JavaScript | WebReference

JavaScript 1.3 Overview, Part II: Changes to the Boolean Object - Doc JavaScript


Changes to the Boolean Object

JavaScript 1.3 changes the way a Boolean object is treated in conditional statements. If you use Boolean objects in your code, you'll better verify that they are used in a 1.3-compliant manner.

In JavaScript 1.2, a Boolean false object was treated as false in conditional tests. Likewise, a Boolean true object was treated as true. In JavaScript 1.3, though, a Boolean object is always treated as true. Let's look at the simplest if statement's syntax, if(condition). When the condition is a Boolean object, JavaScript 1.3 returns a different value than JavaScript 1.2 returned. JavaScript 1.2 returned the value of the Boolean object. If the Boolean object was a false object, the if statement was evaluated to false. If the Boolean object was a true object, the if statement was evaluated to true. JavaScript 1.3 does not care about the value of the Boolean object. It always returns true if the Boolean object exists. In fact, it returns true for any object type, as long as it exists.

The following piece of JavaScript code will yield different results in 1.2 than in 1.3. The 1.2 version:

<SCRIPT LANGUAGE="JavaScript1.2">
a= new Boolean(false);
if (a) document.write("The value of a is " + a);
</SCRIPT>

does not print the message, because the if statement returns the value of the object which is false. The 1.3 version:

<SCRIPT LANGUAGE="JavaScript1.3">
a= new Boolean(false);
if (a) document.write("The value of a is " + a);
</SCRIPT>

does print the message, because the if statement only checks for the existence of the Boolean object and returns true. Notice these JavaScript 1.3's changes affect only user-defined Boolean objects. The behavior of conditional tests have not been changed. For example, tricks for checking the browser identity will continue to work. The following two-line script:

IE4 = (document.all);
if (IE4) alert("This message for IE4"); 

will not print its message under Navigator, because IE4 is false.

https://www.internet.com


Created: September 28, 1998
Revised: September 28, 1998

URL: https://www.webreference.com/js/column26/boolean.html