JavaScript Looping

It’s is not unusual that you have to try more than once in life to achieve your goals; same is applicable to programming.

Loop simply mean round, circle or repeat. Loop execute a block of code for a specified number of times, or while a specified condition is true. JavaScript just like other similar C-styled language has two major types of loops.

For Loop: loop through a block of code for a specific number of times; this means that you are expected to know and specify the number of times the loop will run; the programming term for this is iteration. Below is the syntax for for…Loop.
 
Syntax
for (variable=start; variable<=end; variable=variable+increment){
     Block of code to be executed
}


For example loop may save you a lot of headache if you have to generate or perform an operation involving large number; thousands or millions.
Let’s see some examples.

<html>
<head>
<title> JavaScript For Loop</title>
</head>
<body>
<script type="text/javascript">
 var n;
 for (n=1;n<=10;n++)  {
             document.write("Number " + n + "<br />");
 }
 </script>
 </body>
 </html>


The example above simply generates 10 numbers, see screenshot below.

 

while loop: just like the for…next; while…loop is use to loop through a block of code while a specified condition is true.

syntax

while (condition)
{
  code to be executed;
}


Below is the while…loop equivalent of the for…next.

<html>
<head>
<title> JavaScript While…Loop</title>
</head>
<body>
<script type="text/javascript">
var n=0; //declare the counter
while (n<=10)   {
      document.write("Number: " + n);
      document.write("<br />");
      n++;
}
</script>
</body>
</html>

Note that the increment operator ++ it simply increase n by 1 each time the program loop. We can also write that line as n=n+1, which actually give us the opportunity to rewrite the program to generate only even number.  See the code segment below.

Generate even number from 0 to 20

<script type="text/javascript">
var n=2; //declare counter to start from 2
while (n<=20)
{
   document.write(n +"<br />");
   n = n + 2;
}
</script>

If you look at the program segment above you we notice very little difference from the previous one. First is start by declaring the counter to start from two var n=2, secondly; it increment by two n=n+2.



And the next example produces a 2 multiplication table.
<script type="text/javascript">
var n=1;
while (n<=20){
 document.write(n  + " X 2=" + n * 2 +"<br />");
 n++;
}
</script>


Note: I bolded the code that changes:  
n increase, for example 1,2,3,4,5…20 and n*2 multiply the incremented n by 2, using the multiply operator (*).  This results to 1*2, 2*2, 3*2, 4*2, 5*2….20*2 (this is the arithmetic expression that produce the 2,4,6,8,10,12…40) others are just a text join (using the + sign) to the variable and expression, this are + " X 2=" + and +"<br />"