18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Deployment Issues<br />

In this example, the value document.body.clientWidth is used twice, but it’s retrieved using named<br />

properties (an expensive operation compared to accessing a single variable). You can rewrite this code to<br />

use a local variable instead of accessing document.body.clientWidth twice:<br />

var iClientWidth = document.body.clientWidth;<br />

oDiv1.style.left = iClientWidth;<br />

oDiv2.style.left = iClientWidth;<br />

Note that this example also reduces the algorithmic complexity of the previous code by cutting two calls<br />

to linear algorithms down to one.<br />

Minimize statement count<br />

It stands to reason that the fewer statements a script has, the less time needed for it to execute. You can<br />

minimize the number of statements in <strong>JavaScript</strong> code in numerous ways when defining variables, dealing<br />

with iterating numbers, and using array and object literals.<br />

Define multiple variables<br />

As mentioned earlier in the book, you can use the var statement to define more than one variable at a<br />

time. Further, you can define variables of different types using the same var statement. <strong>For</strong> instance, the<br />

following code block uses four separate var statements to define four variables:<br />

var iFive = 5;<br />

var sColor = “blue”;<br />

var aValues = [1,2,3];<br />

var oDate = new Date();<br />

These four statements can be rewritten to use a single var statement:<br />

var iFive = 5 , sColor = “blue”, aValues = [1,2,3], oDate = new Date();<br />

By eliminating three statements you make this code segment run faster.<br />

Insert iterative values<br />

Any time you are using an iterative value (that is, a value that is being incremented or decremented at<br />

various locations), combine statements whenever possible. Consider the following code snippet:<br />

var sName = aValues[i];<br />

i++;<br />

The two preceding statements each have a single purpose: The first retrieves a value from aValues and<br />

stores it in sName; the second iterates the variable i. These can be combined into a single statement by<br />

inserting the iterative value into the first statement:<br />

var sName = aValues[i++];<br />

This single statement accomplishes the same thing as the previous two statements. Because the increment<br />

operator is postfix, the value of i isn’t incremented until after the rest of the statement executes.<br />

Whenever you have a similar situation, try to insert the iterative value into the last statement that uses it.<br />

591

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

Saved successfully!

Ooh no, something went wrong!