17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5 Boolean()<br />

Conceptual overview of using the Boolean() object<br />

The Boolean() constructor function can be used to create Boolean objects, as well as<br />

Boolean primitive values, that represent either a true or a false value.<br />

In the following code, I detail the creation of Boolean values in <strong>JavaScript</strong>.<br />

Sample: sample52.html<br />

<br />

// Create a Boolean object using the new keyword and the Boolean()<br />

constructor.<br />

var myBoolean1 = new Boolean(false); // Using new keyword.<br />

console.log(typeof myBoolean1); // Logs 'object'.<br />

// Create a Boolean literal/primitive by directly using the number<br />

constructor without new.<br />

var myBoolean2 = Boolean(0); // Without new keyword.<br />

console.log(typeof myBoolean2); // Logs 'boolean'.<br />

// Create Boolean literal/primitive (constructor leveraged behind the<br />

scenes).<br />

var myBoolean3 = false;<br />

console.log(typeof myBoolean3); // Logs 'boolean'.<br />

console.log(myBoolean1, myBoolean2, myBoolean3); // Logs false false<br />

false.<br />

<br />

Boolean() parameters<br />

The Boolean() constructor function takes one parameter to be converted to a Boolean<br />

value (i.e. true or false). Any valid <strong>JavaScript</strong> value that is not 0, -0, null, false,<br />

NaN, undefined, or an empty string ("") will be converted to true. In the following<br />

sample, we create two Boolean object values: One true and one false.<br />

Sample: sample53.html<br />

<br />

// Parameter passed to Boolean() = 0 = false, thus foo = false<br />

var foo = new Boolean(0)<br />

console.log(foo);<br />

67

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!