A “for loop” is quite useful to execute a block of
statements a specified number of times.
Its syntax is:
for (initialize; test; increment)
{
//Statements.
}
- Initialize is a JavaScript statement that sets up the initial value of a variable.
- Test is a logical expression. As long as test is true, the statement executes. As soon as test is false, the statement terminates.
- Increment is JavaScript statement that specifies how the loop variable is changed with each repetition.
Let us take some examples to understand the concept loops:
Suppose you want to execute a set of statements 20 times. To
do it will use the following “for Loop”
statement:
for (var a = 0; a<20; a++)
{
…
}
Now let us see what exactly happens in this loop:
- The variable ‘a’ is declared and initialized to 0. If the variable has already been declared in the whole program somewhere else, then you can simply set its value.
- The expression a < 20 is evaluated. Since it is true at this point, all the statements in the curly braces are executed.
- The statement a++ is executed, increasing the value of a by 1.
- The expression a < 20 is evaluated. It is still true at this point, so all the statements in the curly braces are executed once again.
- The process repeats 20 times, after which a will be equal to 19. When it is incremented to 20, the expression x < 20 evaluates as false, sot the statements in the braces are not executed and execution passes to the line following the “for loop”.
Note
Within the body of the
loop, the loop variable is available for use in your calculations. So the value
of variable can be modified as per the need within the loop.
Exiting a for Loop Early
You can exit a “for loop” early that is, before the test
condition becomes false, with the break
statement. As soon as a break statement is encountered within a loop, execution
immediately exits the loop and continues with the code that follows.
While and Do… While
The while statement executes a part of code repeatedly as
long as a specified condition is true. Its syntax is:
while (condition)
{
//Statements
}
Note
that is starting
condition is false, the statements will not be executed even once.
The do…while statement is a slight different from while statement in which the condition is tested at the end of the loop
rather than at the beginning:
do
{
//statements.
}
while (condition)
The major difference between while and do…while is
that with do…while you are
guaranteed that the statements will be executed at least once.
0 comments:
Post a Comment