06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

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

<strong>JavaScript</strong> Primer<br />

• Use the Boolean() function; this is an ordinary function that returns a<br />

primitive Boolean:<br />

var fBooleanTrue = Boolean(true);<br />

var fBooleanFalse = Boolean(false);<br />

Both these methods return expected truthy or falsy values. However, if you create a<br />

Boolean object using the new operator, things can go really wrong.<br />

Essentially, when you use the new operator and the Boolean(value) constructor,<br />

you don't get a primitive true or false in return, you get an object instead—and<br />

unfortunately, <strong>JavaScript</strong> considers an object as truthy:<br />

var oBooleanTrue = new Boolean(true);<br />

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

console.log(oBooleanTrue); //true<br />

console.log(typeof oBooleanTrue); //object<br />

if(oBooleanFalse){<br />

console.log("I am seriously truthy, don't believe me");<br />

}<br />

>"I am seriously truthy, don't believe me"<br />

if(oBooleanTrue){<br />

console.log("I am also truthy, see ?");<br />

}<br />

>"I am also truthy, see ?"<br />

//Use valueOf() to extract real value within the Boolean object<br />

if(oBooleanFalse.valueOf()){<br />

console.log("With valueOf, I am false");<br />

}else{<br />

console.log("Without valueOf, I am still truthy");<br />

}<br />

>"Without valueOf, I am still truthy"<br />

So, the smart thing to do is to always avoid Boolean constructors to create a new<br />

Boolean object. It breaks the fundamental contract of Boolean logic and you should<br />

stay away from such difficult-to-debug buggy code.<br />

[ 14 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!