04.11.2015 Views

javascript

Create successful ePaper yourself

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

The while Statement<br />

Chapter 3: Language Basics<br />

The while statement is a pretest loop. This means the escape condition is evaluated before the code<br />

inside the loop has been executed. Because of this, it is possible that the body of the loop is never<br />

executed. Here ’ s the syntax:<br />

while(expression) statement<br />

And here ’ s an example of its usage:<br />

var i = 0;<br />

while (i < 10) {<br />

i += 2;<br />

}<br />

In this example, the variable i starts out equal to 0 and is incremented by two each time through the<br />

loop. As long as the variable is less than 10, the loop will continue.<br />

The for Statement<br />

The for statement is also a pretest loop with the added capabilities of variable initialization before<br />

entering the loop and defining postloop code to be executed. Here ’ s the syntax:<br />

for (initialization; expression; post-loop-expression) statement<br />

And here ’ s an example of its usage:<br />

var count = 10;<br />

for (var i=0; i < count; i++){<br />

alert(i);<br />

}<br />

This code defines a variable i that begins with the value 0. The for loop is entered only if the<br />

conditional expression ( i < count ) evaluates to true , making it possible that the body of the code<br />

might not be executed. If the body is executed, the postloop expression is also executed, iterating the<br />

variable i . This for loop is the same as the following:<br />

var count = 10;<br />

var i = 0;<br />

while (i < count){<br />

alert(i);<br />

i++;<br />

}<br />

Nothing can be done with a for loop that can ’ t be done using a while loop. The for loop simply<br />

encapsulates the loop - related code into a single location.<br />

65

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

Saved successfully!

Ooh no, something went wrong!