Core JavaScript

For Loops

A for loop provides the simplest method for iterating over a set of values; this is particularly useful when accessing elements of an array in order. The code example below uses a for loop to count from 0 to 9 and prints the value during each iteration of the loop.

The structure of a for loop statement consists of three parts: the initialization, the conditional, and the update step. The initialization happens only once, immediately when the loop is entered. The conditional is a boolean value that is checked at the very end of the loop and causes the computer to exit when its value becomes false. The update step runs once every loop, after the inner code and before the conditional.

In the code below, the three parts of the for loop are initialization: var i = 0, conditional: i < 10, update step: ++i. So, the initialization declares the variable i and sets it equal to zero when the for loop is entered. The conditional step checks whether i is less than 10 and terminates if it is not at the very end of the loop. The update step increments the variable i during each cycle of the loop just before the conditional is checked.

These three steps can be much more complex and can contain multiple steps or none at all. Of course, the conditional must evaluate to a single boolean value, and if it is left empty the loop will run forever.

ForLoop.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="ForLoop.js"></script>
</body>
</html>

ForLoop.js

// Initialize i to zero and increment for each loop until i = 10.
for (var i = 0; i < 10; ++i) {
	document.writeln("i = " + i + "<br />");
}
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.