The Boolean type is the reference type corresponding to the Boolean values.
To create a Boolean object, use the Boolean constructor and
pass in either true
or false
.
var booleanObject = new Boolean(true);
Boolean reference type overrides the valueOf() method to
return a primitive value of true
or false
.
The toString() method is overridden to return a string of "true" or "false".
var falseObject = new Boolean(false);
var result = falseObject && true;
console.log(result); //true
var falseValue = false;
result = falseValue && true;
console.log(result); //false
In this code, a Boolean object is created with a value of false
.
Then it is ANDed with the primitive value true
.
It should result to false
.
But it is the object named falseObject
being evaluated, not its value ( false
).
All objects are converted to true
in Boolean expressions,
so falseObject
is given a value of true
.
Then, true ANDed with true is equal to true.
The code above generates the following result.
The typeof operator returns "boolean" for the primitive but "object" for the reference.
A Boolean object is an instance of the Boolean type and will return true when used with the
instanceof
operator, whereas a primitive value returns false, as shown here:
var falseObject = new Boolean(false);
var falseValue = false;
console.log(typeof falseObject); //object
console.log(typeof falseValue); //boolean
console.log(falseObject instanceof Boolean); //true
console.log(falseValue instanceof Boolean); //false
The code above generates the following result.