Javascript – while

Loops can execute a block of code a number of times.

The code:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to loop through a block of as long as <em>i</em> is less than 5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i=0;
while (i<5) // If you forget to increase the variable used your browser will crash.
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

The function execute:

document.getElementById("demo").innerHTML=x;

for 5 times, the result is:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

Syntax:
1) It checks the condition
2) It executes the code

while (condition)
  {
  ... you want to do ...
  }

Syntax:
1) It executes the code -> The loop will always be executed at least once, even if the condition is false.
2) It checks the condition

... you want to do ...
  {
  ... you want to do ...
  }
while (condition)

To read an Array:

<!DOCTYPE html>
<html>
<body>

<script>
cars=["BMW","Volvo","Saab","Ford"];
var i=0;
while (cars[i])
{
document.write(cars[i] + "<br>");
i++;
}
</script>

</body>
</html>

My official WebSite >