Chapter 12. Boolean()
Conceptual Overview of Using the Boolean() Object
The Boolean()
constructor
function can be used to create boolean objects, as well as boolean
primitive values, that represent either a true
or a false
value.
In the code below, I detail the creation of boolean values in JavaScript.
<!DOCTYPE html><html lang="en"><body><script> // create boolean object using the new keyword and the Boolean() constructor var myBoolean1 = new Boolean(false); // using new keyword console.log(typeof myBoolean1); // logs 'object' /* create boolean literal/primitive by directly using the number constructor without new */ var myBoolean2 = Boolean(0); // without new keyword console.log(typeof myBoolean2); // logs 'boolean' // create boolean literal/primitive (constructor leveraged behind the scene) var myBoolean3 = false; console.log(typeof myBoolean3); // logs 'boolean' console.log(myBoolean1, myBoolean2, myBoolean3); // logs false false false </script></body></html>
Boolean() Parameters
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() ...
Get JavaScript Enlightenment now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.