While and For Loops
Loops.
In just about every programming language you have studied you have used
some sort of while or for
loops. These structures are most useful for performing repetitive
operations.
The basic syntax and structure of while loops in JavaScript is |
while (condition is true) {
} |
The basic syntax for for loops in JavaScript is |
for (var index=lower ; index < cutoff ;
index++) {
} |
In general,
The for loop has some index that starts at some value, is incremented until it reaches some cutoff. The starting values, conditions on the ending value and the increment can be adjusted in some ways, but this is the essential structure. In many instances, either a for loop or while loop may be used to achieve the desired looping. But the while loop is usually better when the criteria/condition is more vague. And the for loop is better when there are a largely predetermined enumerable number of loops must be executed. Now we will work some examples. Summing the First N Integers With a For Loop. Even though there is a closed formula solution for this problem, a good example to demonstrate arrays is to find the sum of the first N integers where the user is asked to input N. The first program will solve this using a for loop. You should copy the following code and call it SumFor.html. |
<html> <head> <title>Sum the First N Integers Using a For Loop</title> <script language = "JavaScript"> function SumN() { var UpperLimit = window.document.SumForm.txtUpperLimit.value; var Total = 0; for (var i = 1 ; i <= UpperLimit ; i++)
window.document.SumForm.txtTotal.value = Total; |
Most of this code is focused on setting up the form for
user input and output of the solution. The function SumN( ) does
most of the work
The page should look like the following. |
Now we want to solve the problem using a while loop.
Summing the First N Integers With a While Loop. You should copy the following code and call it SumWhile.html. |
<html> <head> <title>Sum the First N Integers Using a For Loop</title> <script language = "JavaScript"> function SumN() { var UpperLimit = window.document.SumForm.txtUpperLimit.value; var Total = 0; var i = 1; while ( i <= UpperLimit)
window.document.SumForm.txtTotal.value = Total; |
Here the only real change is within the function.
The truth is, almost anything that can be done with a for loop can be modified so that it can be done using a while loop, but not vice-a-versa. Though the ease of the adaptations certainly varies. Generally, while loops are more useful when the criteria for cutting them off are something that is changing as the loop executes or something that changes elsewhere in the program. The termination criteria can be more flexible than it usually is for for loops. |