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.

Chapter 1<br />

// GOOD<br />

if ( foo ) ...<br />

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

// BAD:<br />

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

// GOOD<br />

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

// this will also match: 0, "", null, undefined, NaN<br />

// If you MUST test for a boolean false, then use<br />

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

// a reference that might be null or undefined, but NOT false, "" or<br />

0,<br />

// BAD:<br />

if ( foo === null || foo === undefined ) ...<br />

// GOOD<br />

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

// Don't complicate matters<br />

return x === 0 ? 'sunday' : x === 1 ? 'Monday' : 'Tuesday';<br />

// Better:<br />

if (x === 0) {<br />

return 'Sunday';<br />

} else if (x === 1) {<br />

return 'Monday';<br />

} else {<br />

return 'Tuesday';<br />

}<br />

// Even Better:<br />

switch (x) {<br />

case 0:<br />

return 'Sunday';<br />

case 1:<br />

return 'Monday';<br />

default:<br />

return 'Tuesday';<br />

}<br />

[ 37 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!