December 2012
Beginner
164 pages
3h 15m
English
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>
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 ...
Read now
Unlock full access