Thursday 26 December 2013

Javascript : Conditional Statement - Part - 3

Javascript(JS):

The while Loop :
The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.

Syntax:

while (expression){
   executed if expression is true
}
The purpose of a while loop is to execute a statement or code block repeatedly as
long as expression is true. Once expression becomes false, the loop will be exited.

Example:

Following example illustrates a basic while loop:

<script type="text/javascript">
var count = 0;
document.write("Start" + "<br />");
while (count < 10){
  document.write("Count : " + count + "<br />");
  count++;
}
document.write("stopped!");
</script>
Output:

Start
Count : 0
Count : 1
Count : 2
Count : 3
Count : 4
Count : 5
Count : 6
Count : 7
Count : 8
Count : 9
stopped!

The 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.

Syntax:

do{
   Will be executed;
} while (expression);
Note the semicolon used at the end of the do...while loop.

Example:

Let us write above example in terms of do...while loop.

<script type="text/javascript">

var count = 0;
document.write("Loop" + "<br />");
do{
  document.write("Count : " + count + "<br />");
  count++;
}while (count < 0);
document.write("Loop stopped!");

</script>

Output:

Loop
Count : 0
stopped!


The for Loop:

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 the given condition is true or not.
If condition is true then code given inside the loop will be executed otherwise
loop will come out.

The iteration statement where you can increase or decrease your counter.

Syntax:

for (initialization; test condition; iteration statement){
     to be executed if test condition is true
}
Example:

Following example illustrates a basic for loop:

<script type="text/javascript">

var count;
document.write("Loop" + "<br />");
for(count = 0; count < 10; count++){
  document.write("Count : " + count );
  document.write("<br />");
}
document.write("stopped!");

Output:

Start
Count : 0
Count : 1
Count : 2
Count : 3
Count : 4
Count : 5
Count : 6
Count : 7
Count : 8
Count : 9
stopped! 

No comments:

Post a Comment