/

HTML / CSS / JavaScript Tutorial

JavaScript Statement: for

[this page | pdf | back links]

In JavaScript, the for statement identifies a block of statements that are to be executed whilst a condition is true (and a break or to some extent a continue statement have not been triggered).

 

For example, statements such as:

 

     var sumi = 0;

     var i;

     for (i = 1; i <= 5; i++) {sumi = sumi + i}

 

will loop through from i=1 to i=5 and calculate the sum (i.e. 1+2+3+4+5 = 15)

 

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; var x = 0;<br>' +
  'for (i=1; i&lt;=4; i++) {<br>' +
  '&nbsp;&nbsp;x = x + i<br>' +
  '}';
var i; var x = 0;
for (i=1; i<=4; i++) {
  x = x + i
}
document.getElementById("Result").innerHTML = x;
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Reserved Words


Desktop view | Switch to Mobile