04.11.2015 Views

javascript

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

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

Chapter 14: Error Handling and Debugging<br />

The reverseSort() function sorts an array in reverse order, using both the sort() and reverse()<br />

methods. Because of the control condition in the if statement, any non - array value that converts to true<br />

will cause an error. Another common mistake is to compare the argument against null as in this example:<br />

//still unsafe, non-array values cause an error<br />

function reverseSort(values){<br />

if (values != null){ //avoid!!!<br />

values.sort();<br />

values.reverse();<br />

}<br />

}<br />

Comparing a value against null only protects the code from two values: null and undefined (which<br />

are equivalent to using the equal and not equal operators). A null comparison doesn ’ t do enough to<br />

ensure that the value is appropriate; therefore, this technique should be avoided. It ’ s also recommended<br />

that you don’t compare a value against undefined , for the same reason.<br />

Another poor choice is to use feature detection for only one of the features being used. Here is an<br />

example:<br />

//still unsafe, non-array values cause an error<br />

function reverseSort(values){<br />

if (typeof values.sort == “function”){ //avoid!!!<br />

values.sort();<br />

values.reverse();<br />

}<br />

}<br />

In this example, the code checks for the existence of a sort() method on the argument. This leaves open<br />

the possibility that an object may be passed in with a sort() function that is not an array, in which case the<br />

call to reverse() causes an error. When you know the exact type of object that is expected, it ’ s best to use<br />

instanceof as shown in the following example to determine that the value is of the right type:<br />

//safe, non-array values are ignored<br />

function reverseSort(values){<br />

if (values instanceof Array){ //fixed<br />

values.sort();<br />

values.reverse();<br />

}<br />

}<br />

This last version of reverseSort() is safe — it tests the values argument to see if it ’ s an instance of<br />

Array . In this way, the function is assured that any non - array values are ignored.<br />

Generally speaking, values that should be primitive types should be checked using typeof , and values<br />

that should be objects should be checked using instanceof . Depending on how a function is being<br />

used, it may not be necessary to check the data type of every argument, but any public - facing APIs<br />

should definitely perform type checking to ensure proper execution.<br />

484

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

Saved successfully!

Ooh no, something went wrong!