What are the Loops in JavaScript?
Loops are used to execute a segment of code repeatedly until some condition is met. JavaScript's basic looping constructs are (Three Types of LOOP's in JS)
- While loop
- Do...While loop
- For loop
1.while Loop
The while statement executes its statement block as
long as the expression after the while evaluates to true; that is, non-null,
non-zero, non-false. If the condition never changes and is true, the loop will
iterate forever (infinite loop). If the condition is false control goes to the
statement right after the closing curly brace of the loop's statement block.
The break and continue functions are used for loop control.
Syntax:-
while (condition) { statements;
increment/decrement counter;
}
Example:
<html>
<head>
<title>Looping Constructs</title>
</head>
<body>
<h2>While Loop</h2>
<script language="JavaScript">
document.write("<font size='+2'>");
var i=0; // Initialize loop i
while ( i< 10 ){
document.writeln(i);
i++;
} // End of loop block
</script>
</body>
</html>
2.do/while Loop
The do/while statement executes a block of
statements repeatedly until a condition becomes false. Owing to its structure,
this loop necessarily executes the statements in the body of the loop at least
once before testing its expression, which is found at the bottom of the
block.
Syntax:-
do
{ statements;} while (condition);
Example
<html>
<head>
<title>Looping Constructs</title>
</head>
<body>
<h2>Do While Loop</h2>
<script language="JavaScript">
document.write("<font size='+2'>");
var i=0;
do{
document.writeln(i);
i++;
} while ( i< 10 );
</script>
</body>
</html>
3. for Loop
The for loop consists of the for keyword followed by
three expressions separated by semicolons and enclosed within parentheses. Any
or all of the expressions can be omitted, but the two semicolons cannot. The
first expression is used to set the initial value of variables and is executed
just once, the second expression is used to test whether the loop should
continue or stop, and the third expression updates the loop variables; that is,
it increments or decrements a counter, which will usually determine how many
times the loop is repeated.
Syntax:-
for(Expression1;Expression2;Expression3)
{statement(s);} for (initialize; test;
increment/decrement)
{statement(s);}
Example:-
<html>
<head>
<title>Looping Constructs</title>
</head>
<body>
<h2>For Loop</h2>
<script language="JavaScript">
document.write("<font size='+2'>");
for(var i = 0; i< 10; i++ ){
document.writeln(i);
}
</script>
</body>
</html>