Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
The Boolean() constructor
function takes one parameter to be converted to a boolean value (i.e.,
true or false). Any valid JavaScript value that is not
0, −0, null,
false, NaN, undefined, or an empty string(""), will be converted to true. Below, we create two boolean object
values. One true, one false.
<!DOCTYPE html><html lang="en"><body><script> // parameter passed to Boolean() = 0 = false, thus foo = false var foo = new Boolean(0) console.log(foo); // parameter passed to Boolean() = Math = true, thus bar = true var bar = new Boolean(Math) console.log(bar); </script></body></html>
Instances from the Boolean()
constructor, when used with the new
keyword, produce an actual complex object. You should avoid creating
boolean values using the Boolean()
constructor (instead, use literal/primitive numbers) due to the
potential problems associated with the typeof operator. The typeof operator reports boolean objects as
'object', instead of the primitive label
('boolean') you might expect. Additionally, the
literal/primitive value is just faster to write.