Section 1: Introduction
The main strength of any programming language is its ability to process blocks of code repeatedly.
- Computers are especially adept at performing repeated calculations.
- JavaScript, like other programming languages, provides us with various loop structures.
- Statements placed inside loops are executed a set number of times... or even infinitely.
A loop is a control structure that allows a statement or a block of statements to be repeated multiple times.
- Most programming languages provide three basic forms of looping constructs – pre-test loops, post-test loops, and count-controlled loops.
- Looping structures are designed such that the loop will continue until the value of some condition changes from true to false, or in some structures from false to true.
Repetition can be implemented as:
Pre-test loops | while structure |
Post-test loops | do/while structure |
Count-controlled loops | for structure |
Section 2: while loop: Pre-Test Repetition Structure
In pre-test loops the condition is checked before the body of the loop is executed.
JavaScript provides the while structure for pre-test loops.
- In the while structure the loop will execute as long as the condition remains true.
- As soon as the condition becomes false, the loop will terminate, transferring control to the first statement after the repetition structure..
- If the condition is initially false, the loop will not be executed even once.
While there are more items on my shopping list
Purchase next item and cross it off my list
Example: find the first power of 2 larger than 1000.
var product = 2;
while (product <= 1000)
{
product = product * 2;
}
- The condition should be enclosed in parentheses.
- A while repetition structure may have one or more statements in its body.
- The body is enclosed in curly brackets.
- Execution continues with the next statement after the closing bracket.
- The figure below shows the while repetition structure.

A common error is failing to include in the body of a while structure an action that eventually causes the condition in the while to become false. This will normally result in a repetition structure that will never terminate-an error caIled an "infinite loop."
Section 3: do/while loop: Post-Test Repetition Structure
In post-test loops the condition is checked after the body of the loop is executed.
JavaScript provides the do/while loop structure to implement a post test.
- The loop will execute as long as the condition remains true.
- As soon as the condition becomes false, the loop will terminate, transferring control to the first statement after the repetition structure.
- If the condition is initially false, the loop will be executed one time, because the condition is not checked until after the body of the loop.
Since the do/while repetition structure tests the loop-continuation condition after the loop body is performed, the loop body will be executed at least once.
Example: reverse a number
num = document.getElementById("txtNum").value;
do
{
nextDigit = num % 10; // strips off last digit
reversed += nextDigit; // concatenates last digit to reversed
num = parseInt(num / 10); // removes the last digit from num
}
while (num > 0)

Note that the loop-continuation condition is not tested until after the action is performed at least once.
Infinite loops are caused when the loop-continuation condition never becomes false. In a count-controlled loop make sure the control variable is incremented (or decremented) in the body of the loop.
Section 4: Count-Controlled Loops
Count-controlled loops require:
- The name of a loop control variable (or loop counter)
- The initial value of the control variable.
- The increment (or decrement) by which the control variable is modified each time through the loop.
- The condition that tests for the final value of the control variable (i.e., whether looping should continue).
Example:
var beginCelsius = +document.getElementById("txtBeginning").value;
var endCelsius = +document.getElementById("txtEnding").value;
var celsius = beginCelsius;
while (celsius <= endCelsius)
{
fahrenheit = (celsius * 9/5) + 32;
cOutput += celsius + "\n";
fOutput += fahrenheit + "\n";
celsius = celsius + 1;
}
The loop terminates when the control variable exceeds endCelsius.
See an animated demo of a For statement.
Because floating-point values may be approximate, controlling counting loops with floating point variables may result in imprecise counter values and inaccurate tests for termination. (Because JavaScript does not distinguish between integer and real numbers, this is not a major problem. However, it is safer to use a relational operator other than == to specify the loop termination condition.)
for Repetition Structure
The for repetition structure handles all the details of count-controlled repetition.
The previous procedure is rewritten as a for loop below.
Example:
var beginCelsius = +document.getElementById("txtBeginning").value;
var endCelsius = +document.getElementById("txtEnding").value;
for (var celsius=beginCelsius; celsius<=endCelsius; celsius++)
{
fahrenheit = (celsius * 9/5) + 32;
cOutput += celsius + "\n";
fOutput += fahrenheit + "\n";
}
An example of a for loop can be viewed in the Celcius Equivalents demo.
The loop continues as long as the control variable is less than or equal to the final value.
Notes:
- The counter variable is something that is created and usually used only in the for loop to count how many times the for loop has looped.
- The conditional statement decides whether the for loop continues executing or not; this check usually includes the counter variable in some way.
- The initialization statements are executed once; only when the for loop is encountered.
- After execution of initialization statements, the condition is evaluated.
- After every iteration, the loop control variable (lcv) update statements are executed and then the condition is evaluated again.
- This continues until the condition returns false and the loop stops.

Special for notes:
- The starting value, ending value, and update portions of a for structure can contain arithmetic expressions. Example, assuming that x = 2 and y = 10:
- for (var counter = x; counter <= 4 * x * y; counter += y / x)
- is equivalent to the statement
- for (var counter = 2; counter <=80; counter += 5)
- The update portion of a for structure may be negative, in which case it is a decrement and the loop actually counts downwards.
- In nested for loops, using the same control variable name for more than one loop can cause disastrous results.
- If the loop-continuation condition is initially false (i.e., the starting value is greater than the ending value and the increment is positive), the for's body is not performed.
Although the value of the control variable can be changed in the body of a for loop, avoid doing so because this practice can lead to subtle errors.

Note that the initialization occurs only once and that incrementing occurs each time after the body is executed.
Examples:
- Vary the control variable from 1 to 100 in increments of 1.
-
for (var counter = 1; counter <= 100; counter++)
{
// statements in loop body go here
} - Vary the control variable from 100 to 1 in decrements of 1.
- for (var counter = 100; counter >= 1; counter--)
- Vary the control variable from 7 to 77 in increments of 7.
- for (var counter = 7; counter <= 77; counter+=7)
- Vary the control variable from 20 to 2 in decrements of 2.
- for (var counter = 20; counter >= 2; counter–=2)
- Vary the control variable over the following sequence of values: 2, 5, 8, 11, 14, 17, 20.
- for (var counter = 2; counter <= 20; counter+=3)
- Vary the control variable over the following sequence of values: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0.
- for (var counter = 99; counter >= 0; counter–=11)
Section 5: Breaks not allowed!
Avoid the use of break statements to terminate loop execution.
Avoid doing this!
const numGrades = 5;
var grade;
for (var counter = 1; counter <= numGrades; counter++)
{
grade = prompt("Enter grade:", "00");
if (grade < 60)
{
alert("Failing
grade encountered.");
break; // avoid using this in a for loop!
}
}
if (counter > numGrades)
{
alert(" Excellent!\nAll students passed!");
}
Better approach, because a for loop is designed to be a count-controlled loop, and it is expected that it will terminate ONLY when the test condition becomes false. There should be a single exit ONLY!
const numGrades = 5;
var grade;
var allGradesPassed = true;
var counter = 0;
while ((counter <= numGrades) && allGradesPassed)
{
grade = prompt("Enter grade:", "00");
if (grade < 60)
{
alert("Failing
grade encountered.");
allGradesPassed =
false;
}
counter += 1;
}
if (allGradesPassed)
{
alert(" Excellent!\nAll students passed!");
}
Why no breaks?
- Depending on how the interpreter is written, a break may cause an abrupt exit and garbage may be left on the stack. Can you take the chance that some other coder did things correctly?
- Use of break and continue cause problems with refactoring. This might be a sign that this is a bad practice.
- The intent of the code is also clearer when using if statements.
- Break (and return) statements often increase cyclomatic complexity, which makes it harder to prove code is behaving correctly in all cases.
- MISRA coding standards recommend against use of breaks.
- Use of breaks is considered not good practice.
- Folks on StackOverflow debate this and feel break is mostly okay, but they are not grading your assignments.