Javascript loops

Loops are used in javascript to execute a same piece of code for a number of times. Basically, for ,do - while, while loops are used depending upon the conditions.

For loop
<html>
<body>
<script type='text/javascript'>
var i=0;
for (i=0;i<=5;i++)
{
document.write('The number is ' + i);
document.write('<br />');
}
</script>
</body>
</html>

The code above executes for 5 times and prints the value of i . For loop is used when we have to execute a statement fixed number of times. However, if we dont know how many times we need to execute a function, we use a while loop more preferably.

While loop

Suppose we have to do some operation on a set of values of an array, we need to use a while loop which operates till the value of the array finishes off. Here is an exaple explaining the same :-

var sum = 0;
var pos = 0;
while(array[pos]!=""){
   sum += array[pos];
   pos++;
   }

Since , we are done with the basics of the javascript, lets see some javascript in action i.e. running javascript applications.

Member Login

Member Login




Not a Member? Sign Up!




Login to comment

Be the first to comment on this topic







  


<<< Wanna review

Continue >>>