18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

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

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

Chapter 19<br />

<strong>JavaScript</strong> gotchas<br />

<strong>JavaScript</strong>, as you are well aware at this point, is unlike other programming languages in many ways.<br />

Therefore, it helps to keep in mind some of the gotchas of the language.<br />

Avoid string concatenation<br />

Earlier in the book, you learned about the hazards of string concatenation using the plus (+) operator. To<br />

work around this problem, you learned how to create a StringBuffer object to encapsulate string concatenations<br />

using an Array and the join() method.<br />

Whenever you are doing more than five string concatenations in a row, it’s best to use the StringBuffer<br />

object.<br />

Use built-in methods first<br />

Whenever possible, use built-in methods of <strong>JavaScript</strong> objects before making your own. The built-in<br />

methods are compiled in C++ and as such, run much faster than <strong>JavaScript</strong> that must be interpreted on<br />

the fly. <strong>For</strong> example, you could write a function that calculates the value of a number when raised to the<br />

power of n in this way:<br />

function power(iNum, n) {<br />

var iResult = iNum;<br />

for (var i=1; i < n; i++) {<br />

iResult *= iNum;<br />

}<br />

}<br />

return iResult;<br />

Although this function works perfectly well, <strong>JavaScript</strong> already provides a way to calculate the power of<br />

a number by using Math.pow():<br />

alert(Math.pow(3, 4));<br />

//raise 3 to the 4th power<br />

The big difference is that Math.pow() is part of the browser, written and compiled in C++, and it is<br />

much faster than the custom power() function defined previously.<br />

Numerous built-in methods are provided specifically to take care of these common tasks. It’s always better<br />

for execution time to use built-in methods instead of functions you define.<br />

Store commonly used values<br />

Whenever you use the same value more than once, store it in a local variable for easy access. This is<br />

especially true for values that are normally accessed through a property of an object. Consider the following<br />

code:<br />

oDiv1.style.left = document.body.clientWidth;<br />

oDiv2.style.left = document.body.clientWidth;<br />

590

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

Saved successfully!

Ooh no, something went wrong!