Beework Web Design Logo

  Search

  

Skype: beeworkweb
Email:info@beework.net

Sales (free):
0800 882 4173

Support:
0870 978 0583

Mobile:
07866 627185

Registered Member of the UK Web Design Association 
Registered Member
of the UK Web Design
Association

Valid XHTML 1.0 Strict



Generate the JavaScript Code for a While Statement

Generates the JavaScript code for a while loop statement. Specify how many times you want the action to occur and click the Generate Code button.

Number of Repeats
Copy and paste this code to the <HEAD> section of your page

while statement

A while statement repeats a loop as long as a specified condition evaluates to true. A while statement looks as follows:

while (condition) {
          
statements
}
If the condition becomes false, the statements within the loop stops executing and control passes to the statement following the loop.

The condition test occurs only when the statements in the loop have been executed and the loop is about to be repeated. That is, the condition test is not continuous but is performed once at the beginning of the loop and again just following the last statement in statements, each time control passes through the loop.

Example 1. The following while loop iterates as long as n is less than three:

n = 0
x = 0
while( n < 3 ) {
          n ++
          x += n
}
With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:

  • After the first pass: n = 1 and x = 1
  • After the second pass: n = 2 and x = 3
  • After the third pass: n = 3 and x = 6 After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

    Example 2: infinite loop. Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate. The statements in the following while loop execute forever because the condition never becomes false:

    while (n<3) {
              alert("Hello, world") }