17.11.2015 Views

JavaScript_Succinctly

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Boolean object via the Boolean() constructor, the value itself converts to true. In the<br />

following sample, I demonstrate how a false Boolean object is always "truthy.”<br />

Sample: sample54.html<br />

<br />

var falseValue = new Boolean(false);<br />

console.log(falseValue); // We have a false Boolean object, but objects<br />

are truthy.<br />

if (falseValue) { // Boolean objects, even false Boolean objects, are<br />

truthy.<br />

console.log('falseValue is truthy');<br />

}<br />

<br />

If you need to convert a non-Boolean value into a Boolean, just use the Boolean()<br />

constructor without the new keyword and the value returned will be a primitive value<br />

instead of a Boolean object.<br />

Certain things are false, everything else is true<br />

It has already been mentioned, but is worth mentioning again because it pertains to<br />

conversions: If a value is 0, -0, null, false, NaN, undefined, or an empty string(""), it<br />

is false. Any value in <strong>JavaScript</strong> except the aforementioned values will be converted to<br />

true if used in a Boolean context (i.e. if (true) {};).<br />

Sample: sample55.html<br />

<br />

// All of these return a false Boolean value.<br />

console.log(Boolean(0));<br />

console.log(Boolean(-0));<br />

console.log(Boolean(null));<br />

console.log(Boolean(false));<br />

console.log(Boolean(''));<br />

console.log(Boolean(undefined));<br />

console.log(Boolean(null));<br />

// All of these return a true Boolean value.<br />

console.log(Boolean(1789));<br />

console.log(Boolean('false')); // 'false' as a string is not false the<br />

Boolean value.<br />

69

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

Saved successfully!

Ooh no, something went wrong!