/

HTML / CSS / JavaScript Tutorial

JavaScript Statement: while

[this page | pdf | back links]

In JavaScript, the while statement identifies block of statements that is repeatedly executed while a condition is true.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
document.getElementById("Example").innerHTML =
  'var i = 1;<br>' +
  'var x = 0;<br>' +
  'while (i&lt;=4) {<br>' +
  '&nbsp;&nbsp;x = x + i;<br>' +
  '&nbsp;&nbsp;i++;<br>' +
  '}';
var i = 1;
var x = 0;
while (i<=4) {
  x = x + i;
  i++;
}
document.getElementById("Result").innerHTML = x;
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Reserved Words


Desktop view | Switch to Mobile