JavaScript while loops

There are two forms of while loop in JavaScript, one has the controlling test at the start of the loop, the other starts with a do command and has the test at the end.

var pwd="";
while (pwd !="secret")
  {
  pwd = prompt("Enter the password...");
  }

The other starts with the Do statement and has the test at the end of the loop. In this case we don't need to give a value to the pwd string before the start of the loop. The value won't be needed until we get to the test at the end of the string and by then we'll have a value from the prompt:

do
  {
  pwd = prompt("Enter the password...");
  }
while (pwd !="secret")

It may seem that this second form of the loop is always going to be the better one to choose but it does have a drawback. The program will enter the loop and execute the statements in the body before meeting the test condition. This means that the loop will always execute at least once and sometimes this isn't what we want to happen.

MS Access technical tips

Visual FoxPro technical tips

General Tips

 

More tips from Alvechurch Data

Search page for Alvechurch Data

Searching a web site with JavaScript

Read More

Site Map

Site map of the Alvechurch Data site

Read More

Javascript for loops

Javascript for loops

Read More

Repetition in Javascript

JavaScript structures for repetition

Read More

Javascript if...else structure

Javascript if ... else structure

Read More