The for statement is a loop executing kind of a statement used to pre-test code's flow conditions.

This type of a statement is the most popular loop execution statement. The reason for that is due to a fact that a single line of code does all three crucial parts of any loop iteration at once; in other words, a variable or variables get initialized, the expression set, and the iteration started, all at once. The example below explains it better:

for (variables initialization; expression; iteration) {

   statement;

}

Or with the real numbers situation:

var counter = 5;

for (var i=0; i<counter; i++) {

   alert(i);

}

Another advantage of a for loop is that it is very versatile; for instance the variables i and counter may be defined, in or out of the loop; or may even be omitted in which case the semicolons must not be excluded (i.e. for (; i<counter; ).

The forloop statement is called a pretesting because the expression (above: i<counter) is tested before the loop starts and if it fails, the loop will never initiate.

Example

The example with for statement in JavaScript:

x
 
<!DOCTYPE html>
<html>
<head>
<title>JS tutorial</title>
<style type="text/css">
body {
    margin-top:10px; padding:0px;
    background-color:#ddd;
    font-family:cursive; font-size:0.9em; color:#223;
}
input, #result, #title {
    padding:2px;
    font-family:cursive; font-size:1.0em; color:#223;
    cursor:pointer;
}
#result {
    font-size:0.8em;
}
</style>
<script type="text/javascript">
    function convertDeg() { 
        var title = document.getElementById("title"); 
        var result = document.getElementById("result");
        result.textContent = "";
        title.textContent = "C ----> F";
        for (c = 0, f = 0; c <= 100; c +=13) {
            f = parseInt((c * 1.8) + 32);
            result.textContent += c + " ----> " + f + "\n";
        }           
    }
</script>   
</head>
<body>
    <h5>This <i>for</i> statement converts Celsius to Fahrenheit:</h5>
    <form action="" method="post">
    <input type="button" onclick="convertDeg()" value="START" />
    </form>
    <pre id="title">&nbsp;</pre>
    <pre id="result">&nbsp;</pre>
</body>
</html>

 

›› go to examples ››