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

Data Type Errors<br />

Since JavaScript is loosely typed, variables and function arguments aren ’ t compared to ensure that the<br />

correct type of data is being used. It is up to you, as the developer, to do an appropriate amount of data<br />

type checking to ensure that an error will not occur. Data type errors most often occur as a result of<br />

unexpected values being passed into a function.<br />

In the previous example, the data type of the third argument is checked to ensure that it ’ s a string, but<br />

the other two arguments aren ’ t checked at all. If the function must return a string, then passing in two<br />

numbers and omitting the third argument easily breaks it. A similar situation is present in the following<br />

function:<br />

//unsafe function, any non-string value causes an error<br />

function getQueryString(url){<br />

var pos = url.indexOf(“?”);<br />

if (pos > -1){<br />

return url.substring(pos +1);<br />

}<br />

return “”;<br />

}<br />

The purpose of this function is to return the query string of a given URL. To do so, it first looks for a<br />

question mark in the string using indexOf() and if found, returns everything after the question mark<br />

using the substring() method. The two methods used in this example are specific to strings, so any<br />

other data type that is passed in will cause an error. The following simple type check makes this function<br />

less error prone:<br />

function getQueryString(url){<br />

if (typeof url == “string”){ //safer with type check<br />

var pos = url.indexOf(“?”);<br />

if (pos > -1){<br />

return url.substring(pos +1);<br />

}<br />

}<br />

return “”;<br />

}<br />

In this rewritten version of the function, the first step is to check that the value passed in is actually a<br />

string. This ensures that the function will never cause an error because of a nonstring value.<br />

As discussed in the previous section, using non - Boolean values as conditions for flow control statements<br />

is a bad idea because of type coercion. This is also a bad practice that can cause data type errors.<br />

Consider the following function:<br />

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

function reverseSort(values){<br />

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

values.sort();<br />

values.reverse();<br />

}<br />

}<br />

483

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

Saved successfully!

Ooh no, something went wrong!