JavaScript & jQuery Tutorials

JS Home Right Arrow JS Reference Right Arrow while

while statement

Creates a loop structure that may or may not be executed.

Description

Creates a loop through a section of code which will be executed while a condition remains true. If the condition is false to begin with the loop doesn't execute.

Syntax


Signature Description
while (condition)
   statement
Creates a loop through a section of code which will be executed while a condition remains true.
  • If the condition is false to begin with the loop doesn't execute.

Parameters


Parameter Description
conditionAn expression that evaluates to true or false and is tested before each pass through the loop.
statementExecuted when expression evaluates to true.

Examples

The code below shows some while loops.




// execute the loop till a condition met.
var aVariable = 1;

while (aVariable < 10) {
  alert('aVariable = ' + aVariable);
  aVariable += 4;
}
alert('left first while loop');


// this loop will never execute.
var bVariable = 11;

while (bVariable < 10) {
  alert('bVariable = ' + bVariable);
  bVariable += 4;
}
alert('left second while loop');


Press the button below to action the above code:



Related Tutorials

JavaScript Intermediate Tutorials - Lesson 4 - While and Do....While Loops




  

go to home page Homepage go to top of page Top