JavaScript Programming Programming Languages Web Development
JavaScript for Loop Control Statement
October 22, 2018 Tanmay Sakpal 0 Comments for loop, for loop in javascript, javascript for loop
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:
1for (initialization condition; testing condition; increment/decrement)
2{
3 statement(s)
4}
1. 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.
2. 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.
3. Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.
4. Increment/ Decrement: It is used for updating the variable for next iteration.
5. Loop termination:When the condition becomes false, the loop terminates marking the end of its life
cycle.
Flow Chart:
Program example –
1 <html>
2 <body>
3
4 <script type="text/javascript">
5 <!--
6 var count;
7 document.write("Starting Loop" + "<br />");
8
9 for(count = 0; count < 10; count++){
10 document.write("Current Count : " + count );
11 document.write("<br />");
12 }
13
14 document.write("Loop stopped!");
15 //-->
16 </script>
17
18 <p>Set the variable to different value and then try...</p>
19 </body>
20</html>
Output –
1 Starting Loop
2 Current Count : 0
3 Current Count : 1
4 Current Count : 2
5 Current Count : 3
6 Current Count : 4
7 Current Count : 5
8 Current Count : 6
9 Current Count : 7
10Current Count : 8
11Current Count : 9
12Loop stopped!
13Set the variable to different value and then try...