Changes

Jump to: navigation, search

JavaScript Flow Control and Looping

1,185 bytes added, 13:18, 24 April 2007
JavaScript ''while'' loops
== JavaScript ''while'' loops ==
 
The ''for'' loop described above works well when you knmow how many times a particialr task needs to be repeated. Clearly there will often be instances where something needs to be repeated until a certain condition is met, with no way of knowing how many repetitions are going to be needed to meet that condition. To address this need javaScript provides the ''while'' loop. In essense the ''while'' loop repeats a set of tasks until a specified condition is met. The ''while'' loop syntax is as follows:
 
while (''condition'')
{
''JavaScript Statements''
}
 
where ''condition'' is an expression that will return either ''true'' or ''false'' and ''JavaScript Statements'' represents the JavaScript to be executed while the expression is ''true''. For example:
 
<pre>
while ( i < 10 )
{
i = i + j;
}
 
</pre>
 
In the above example the ''while'' expression will evaluate whether i is less than 10. If it is already greater than 10 then the code in the braces is skipped. If it is not greater than 10 the code in the braces is executed and the loop returns to while statement and repeats the evaluation of i. This process repeats until i is greater than 10 at which point the loop exits.

Navigation menu