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 />

The following example shows you how to type cast using Booleans:<br />

const age = 0; // bad<br />

const hasAge = new Boolean(age); // good<br />

const hasAge = Boolean(age); // good<br />

const hasAge = !!age;<br />

Conditional evaluation<br />

There are various stylistic guidelines around conditional statements. Let's study the<br />

following code:<br />

// When evaluating that array has length,<br />

// WRONG:<br />

if ( array.length > 0 ) ...<br />

// evaluate truthiness(GOOD):<br />

if ( array.length ) ...<br />

// When evaluating that an array is empty,<br />

// (BAD):<br />

if ( array.length === 0 ) ...<br />

// evaluate truthiness(GOOD):<br />

if ( !array.length ) ...<br />

// When checking if string is not empty,<br />

// (BAD):<br />

if ( string !== "" ) ...<br />

// evaluate truthiness (GOOD):<br />

if ( string ) ...<br />

// When checking if a string is empty,<br />

// BAD:<br />

if ( string === "" ) ...<br />

// evaluate falsy-ness (GOOD):<br />

if ( !string ) ...<br />

// When checking if a reference is true,<br />

// BAD:<br />

if ( foo === true ) ...<br />

[ 36 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!