LILLY ROBOT |
In programming writing the same codes over and over again can be very tedious and time consuming. In JavaScript if you want to repeat a block of codes several times you can use one of the Loops. Let us look at different types of Loops.
The For loop is used if you know how many times you want your codes to be repeated.
for (var= start(initial value); condition; increment++/decrement--)
{
statment to be executed
}
If a condition inside the for loop is true then the statement inside the curly bracket is executed. The increment/decrement counter will continue to increase/decrease by 1 until the condition is no longer true.
Displays
In the while loop if the condition is true the statment(s) inside the curly bracket continues to be
executed until the condition is false. The increment/decrement counter is after the statement.
You can create an infinitive loop with the syntax while(true).
while (condition)
{
Statement(s) is executed if condition is true;
}
increment++/decrement--
Displays
Displays
In the do while loop the condition is at the end, so it will be executed at least once. Whereas, in the while loop the statment may never be excuted if the condition remains false.
do
{
Statement(s) to be executed;
}
while (condition);
Displays
The 'for in loop' is used when you want to loop through the properties and methods of an object.
for (variablename in object)
{
statement to be executed
}
Displays
You have already seen the break statment in the switch loop. If you want to exit the loop at anytime you can do so by using the break statement.
Displays
The continue statement breaks where you want it to and then continues on to the end of the loop.
Displays