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) { statement block; }

 The basic syntax for for loops in JavaScript is

 for (var index=lower ; index < cutoff ; index++) { statement block; }

 In general, while loops continue based on some criteria for loops are based more directly on enumeration of a predetermined number of loops 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.

 Sum the First N Integers Using a For Loop Sum the First N Integers Using a For Loop

Input for the number of integers to sum

Output for the sum

 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 obtaining the input from the txtUpperLimit using a for loop to sum the first N integers up to and including UpperLimit outputting the results to the txtTotal 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.

 Sum the First N Integers Using a For Loop Sum the First N Integers Using a For Loop

Input for the number of integers to sum

Output for the sum

 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.