Loop Javascript
Loop Javascript
Loops: Loops can be used to execute the same code over and over again, particularly useful when
dealing with arrays as shown in figure 3.3. JavaScript supports different kinds of loops described below:
• for - loops through a block of code a number of times
• do/while - also loops through a block of code while a specified condition is true
*For Loop:- The for loop is best suited when you already know the number of times the
statements should be executed. the loop executes until the condition becomes false.
//statements
1. The initializing expression is get executed and this expression usually initializes one or more loop
variables.
2. The condition expression is evaluated. if the value of condition is true, the loop statements are
executed. if the value of condition is false, for loop terminates.
3. The increment expression executes and increments the value by the specified step value.
Example1:
<!DOCTYPE html>
Example2:
{
document.write("LITTLE FLOWER SCHOOL, GIDA GORAKHPUR " +"<br>");
Note: We can omit statement 1 when the values are set before the loop starts:
Example3:
var i=0;
Example4 :
Example5:
var i=0;
for (; i <5;)
i++
}
*While loop: The While loop is another commonly used loop in JavaScript. the purpose of the
while loop is to execute a block of statements over and over again until the condition fails. it is best
suited in a scenario where we don’t know in advanced as to how many times the loop will be executed.
while (condition)
Statement-1;
Statement-2; }
Example1: Print Little Flower School Gida, Gorakhpur 5 times.
<!DOCTYPE html>
var i=0;
while( i < 5)
i++;
<!DOCTYPE html>
var i=1;
while( i <=5)
document.write(i+"," +"<br>");
i++;
<!DOCTYPE html>
var i=5;
while( i >=5)
document.write(i+"," +"<br>");
i--;
}
</script> </body> </html>
*do While loop This is another kind of loop and different from the for loop and the while loop.
this loop will execute the statement at least once that is the statements inside the loop will always get
executed at least once, even if the condition is false. the condition is checked happens after the loop has
been executed. the loop will continue to execute or will terminate according to on the condition.
do
Statement1;
Statement2
} while (Condition)
<!DOCTYPE html>
var i=0;
do
i++;
} while( i < 5)
<!DOCTYPE html>
var i=1;
do
document.write(i+"," +"<br>");
i++;
} while( i < 5)
<!DOCTYPE html>
var i=5;
do
document.write(i+"," +"<br>");
i--;
} while( i >=5)
For..in Loop:The for/in loop: the JavaScript for/in statement loops through the properties of
an object explain below.
<!DOCTYPE html>
var x;
for (x in person) {
document.write(text);