JavaScript for Loop Control Statement
Loops can execute a block of code a number of times. Loops are handy, if you want to run the same code over and over again, each time with a different value.
The ‘for‘ loop is the most compact form of looping. It includes the following three important parts −
- The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
- The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
- The iteration statement where you can increase or decrease your counter.
For loop is primarily preferred when the number of iterations are well known in advanced.
Syntax:
for (initialization condition; testing condition; increment/decrement) { statement(s) }
- Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
- Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
- Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
- Increment/ Decrement: It is used for updating the variable for next iteration.
- Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle.
Flow Chart:
Program example –
<html> <body> <script type="text/javascript"> <!-- var count; document.write("Starting Loop" + "<br />"); for(count = 0; count < 10; count++){ document.write("Current Count : " + count ); document.write("<br />"); } document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html>
Output –
Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped! Set the variable to different value and then try...