If you want to go down with compact looping, then the best available tool for achieving it is for looping. Following is the explanation for some important terms that are frequently used when dealing with for loops.
The initialization of the counter for it to have a value to start with is known as loop initialization. The execution of the statements that are initialized in the process of the loop of loop initialization takes place at the beginning of the loop (before the loop actually starts to execute).
Usually, a statement is written, which is used to find the value for the given condition ( the value outputs as either true or false). These statements are called test statements. When the value for the given condition outputs as true, then the block of code written inside the loop is executed, and when the value for the given condition outputs as false the control drops out of the provided loop.
Also, in some situations, increasing and decreasing the defined counter is required. This can be achieved by using iteration statements.
They are easy to define in JavaScript code and can be represented in a single line where they are separated from each other with the help of semicolons.
Following is the syntax used for for loop in JavaScript code:
for (initialization; test condition; iteration statement) {
The Statement that has to be executed if the above expression holds the value true
}
Following is an example of a JavaScript code using above mentioned for loop:
<html>
<body>
<script type = "text/javascript">
<!--
var attempts;
document.write("Number of attempts" + "<br />");
for(count = 2; count < 15; count++) {
document.write("Present attempts : " + count );
document.write("<br />");
}
document.write("Loop ended");
//-->
</script>
</body>
</html>
The output for the program is
Number of attempts
Present attempts: 2
Present attempts: 3
Present attempts: 4
Present attempts: 5
Present attempts: 6
Present attempts: 7
Present attempts: 8
Present attempts: 9
Present attempts: 10
Present attempts: 11
Present attempts: 12
Present attempts: 13
Present attempts: 14
Loop ended