Saturday, 4 August 2012

Learning JavaScript tutorial – JavaScript for (loop) Statement

JavaScript for loop is on of the most commonly used loop statement which provides a looping construct that is often more convenient than the while loop statement. JavaScript for loop statement allows you to repeat a section of code a certain number of times; changing values of variable counter by increment or decrement it each time the code is executed.
JavaScript for loop is the most compact form of looping which includes for loop initialization, for loop test case statement, and loop control statement all in one line. The JavaScript for loop statement initialise variable counter at the start of the execution of the loop. Then it checks if the expression evaluates to true, then only for loop statement execute the body of the loop; means the piece of code between the curly brackets and change the value of variable counter by increment or decrement it. For loop perform some action on a piece of code till the test case condition statement is satisfied or evaluate true.

JavaScript for loop statement Syntax

for (loop initialization, loop test case statement, loop control statement)
{
  statement block executed while conditional expression
  evaluates to true(satisfied).
}
Here, If the resulting value of test case conditional expression is true or it is evaluated true, for loop execute statement block enclosed within the Curly braces – {} and new value of variable counter is calculated.
JavaScript for Statement Flowchart
for loop statement flowchart

JavaScript for loop statement example

<script type="text/javascript">
for (var iCount=0;iCount<5;iCount++)
{
  document.write("iCount is – "+ iCount +"<br />");
}
</script>
We have created a local loop variable (var iCount=0;) ‘iCount’ and assigns it an initial value of 0. This initial value is used to define starting point for the loop. Then we evaluate the loop conditional statement (iCount<5;). If it is ‘true’ loop body get executed. Execution of the loop takes place till the loop conditional statement is satisfied i.e. it evaluates ‘true’. The last statement in the for loop set (iCount++) determines the rate at which the local variable value eighter increment or decrement.
In the above example we have defined, for loop local veriable iCount=0 and instruct loop to execute till it is less then 5; at the end of each loop iteration we are going to increment it by 1. Based on this scenario the loop is getting executed 5 times and gives us output as shown in figure below:
JavaScript for Statement Output
for loop statement output

No comments:

Post a Comment