Loops in Javascript
Published by: Anil K. Panta
Loops
While Loops
The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.
Flow Chart
Syntax
while (expression) {
Statement(s) to be executed if expression is true
}
do...while Loop
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.
Flow Chart
Syntax
do {
Statement(s) to be executed;
} while (expression);
Note − Don’t miss the semicolon used at the end of the do...while loop.
For Loop
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.
Flow Chart
Syntax
for (initialization; test condition; iteration statement) {
Statement(s) to be executed if test condition is true
}
for...in loop
The for...in loop is used to loop through an object's properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful.
Syntax
for (variablename in object) {
statement or block to execute
}
In each iteration, one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.