Wednesday, March 5, 2014

Loop in Javascript

Types of loop in Javascript

for loop: The for loop repeats itself for the fixed number of time and it is used when you know that how many times the loop repeats itself.

Syntax:

for(initialization; condition; iteration){//start of loop body
          statement 1 ...
          statement 2 ...
          statement 3 ...
}//end of loop body

Code :
 <!DOCTYPE html>
<head>
<script>
function iterate(){
for(var i=0; i<5; i++) {
counter++;
document.write(counter+"<br/>");
}
</script>
</head>
<body>
<input type="submit" value="Hit" onClick="iterate()">
</body>
 </html>

while loop: A while loop will always evaluates the condition first. While the condition is true it repeats the block.

Syntax:

while(condition) {
        statement 1 ...
        ...
}

Code:
 <!DOCTYPE html>
<head>
<script>
var counter = 0;
function iterate(){
while(counter<5) {
document.write(counter+"<BR>");
counter++;
}
}
</script>
</head>
<body>
<input type="submit" value="Hit" onClick="iterate()">
</body>
 </html>

do while loop: do while loop also iterate itself on the condition but either condition is false it repeats itself at least once, it is also called as post-test loop because condition is tested when the block is executed.

Syntax

do {
    statement 1...
    ...
}while(condition)

Code:
 <!DOCTYPE html>
<head>
<script>
var counter = 0;
function iterate(){
do {
counter++;
document.write(counter+"<br/>");
}while(counter<6);
}
</script>
</head>
<body>
<input type="submit" value="Hit" onClick="iterate()">
</body>
 </html>



No comments:

Post a Comment