Main Page

JavaScript gotchas

JavaScript gotchas
JavaScript, as you are well aware at this point, is unlike other programming languages in many ways.
Therefore, it helps to keep in mind some of the
of the language.
Avoid string concatenation
Earlier in the book, you learned about the hazards of string concatenation using the plus (
) operator. To
work around this problem, you learned how to create a
object to encapsulate string con-
catenations using an
and the
Whenever you are doing more than five string concatenations in a row, it’s best to use the
Use built-in methods first
Whenever possible, use built-in methods of JavaScript objects before making your own. The built-in
methods are compiled in C++ and as such, run much faster than JavaScript that must be interpreted on
the fly. For example, you could write a function that calculates the value of a number when raised to the
power of
in this way:
function power(iNum, n) {
var iResult = iNum;
for (var i=1; i < n; i++) {
iResult *= iNum;
return iResult;
Although this function works perfectly well, JavaScript already provides a way to calculate the power of
a number by using
alert(Math.pow(3, 4)); //raise 3 to the 4th power
The big difference is that
is part of the browser, written and compiled in C++, and it is
much faster than the custom
function defined previously.
Numerous built-in methods are provided specifically to take care of these common tasks. It’s always bet-
ter for execution time to use built-in methods instead of functions you define.
Store commonly used values
Whenever you use the same value more than once, store it in a local variable for easy access. This is
especially true for values that are normally accessed through a property of an object. Consider the fol-
lowing code: = document.body.clientWidth; = document.body.clientWidth;
Chapter 19
22_579088 ch19.qxd 3/28/05 11:43 AM Page 590

JavaScript EditorFree JavaScript Editor     Ajax Editor