Boolean object
Represents a boolean value as an object.
In JavaScript, the true and false keywords represent primitive boolean values. Event though the data type of these boolean primitives is boolean, they are not instances of the Boolean object.
The JavaScript interpreter does not use the Boolean object for implicit data type conversion (when a non-boolean value needs to be converted to boolean, for example in an if statement), but the Boolean object can be used as a function to convert a value to a primitive boolean value explicitly. See Example 3 for details.
When the JavaScript interpreter needs to convert a primitive boolean value to an object, it uses the Boolean object. Example 5 illustrates this mechanism.
Syntax:
Creating a new Boolean object:
var bol = new Boolean ([initState]);
If initState is not specified, the created Boolean object represents false.
When initState is specified and its value is 'true' (converted to a primitive boolean type if needed), then the Boolean object represents true, in any other cases false.
Members:
The Boolean object inherits from the Boolean.prototype and Function.prototype objects.
The following lists only contain the members of the Boolean and Boolean.prototype objects.
(*) - The property is inherited from the Boolean.prototype.
(*) - The method is inherited from the Boolean.prototype.
Properties:
Property | Support | Description | |||||
---|---|---|---|---|---|---|---|
prototype | Returns a reference to the Boolean.prototype object. The Boolean.prototype object allows adding properties and methods to the Boolean object, which can be used with instances of the Boolean object, like any predefined property or method. The prototype property is static, it cannot be accessed from an instance of the Boolean object, only Boolean.prototype is allowed. |
(*) - The property is inherited from the Boolean.prototype.
Methods:
Method | Support | Description | |||||
---|---|---|---|---|---|---|---|
toSource ( )* | Returns a string representing the source code of the current Boolean object. | ||||||
toString ( )* |
Returns a string representing the value of the current Boolean object.
When a boolean needs to be converted to a string, the JavaScript interpreter automatically calls its toString method. |
||||||
valueOf ( )* | Returns the primitive value of the Boolean object. |
(*) - The method is inherited from the Boolean.prototype.
Examples:
Example 1:
Creating Boolean objects with an initial value of false:
Example 2:
Creating Boolean objects with an initial value of true:
Example 3:
Converts a value to a primitive boolean value explicitly with the Boolean function:
Example 4:
A Boolean object always evaluates to true in a condition regardless of whether it represents true or false value.
Example 5:
Adding a new method to the Boolean object and calling it for a primitive boolean value:
|
External links:
User Contributed Comments