JavaScript with loops

Your JavaScript scripts can do all sort of clever stuff like calculating discounts, comparing values, and making choices. However, don't forget we're dealing with machine language, and machines are very good at doing some things us humans would keep a mile off if only we could.

One really boring thing most of us would happily avoid doing is repetitive stuff. You might find it hard to believe this, but JavaScript loves repetition. So much so that it has a special construct for it: the loop.

Here's what you will learn in this lesson:
  • the for loop;
  • the while loop;
  • the do ... while loop.
In the process, you will also learn how to:
  • use getElementById(element Id) to manipulate an HTML element with JavaScript;
  • generate random numbers with random() and floor(number);
  • insert HTML mark-up dynamically with innerHTML.
This is going to be a meaty lesson. Get ready for it!

Loops

At times you will have to repeat some piece of code a number of times:
for instance: a web page has 10 radio buttons and your script needs to find out which radio button was checked by the user.

To do so, your script has to go over each single radio button and verify whether its checked attribute is set to true or false. Does this mean having to write this kind of verification code 10 times?

Thankfully, it does not. You dump the code in a loop once, and it's going to execute any number of times you set it to.

Any loop is made of 4 basic parts:
  1. the start value

    An initial value is assigned to a variable, usually called i (but you can call it anything you like). This variable acts as counter for the loop.
  2. the end value or test condition

    The loop needs a limit to be set: either a definite number (loop 5 times) or a truth condition (loop until this condition evaluates to true). Failing this, you run the risk of triggering an infinite loop. This is very bad: it's a never-ending repetition of the same code that stops users' browsers from responding. Avoid infinite loops at all costs by making sure you set a boundary condition to your loops;
  3. the action or code to be executed

    You type a block of code once and it'll be executed the number of times between your start value and end value;
  4. the increment

    This is the part that moves the loop forward: the counter you initialize has to move up (or down in case you opt for looping backwards). As long as the loop does not reach the end value or the test condition is not satisfied, the counter is incremented (or decremented). This is usually done using mathematical operators.

The for Loop

This kind of loop, well ... loops through a block of code a set number of times. Choose a for loop if you know in advance how many times your script should run.
Here's its basic structure:

 
   //loop for the number of times between start value
 
   //and end value.  Increment the value each time
 
   //the limit has not been reached.
 
   for (var=startvalue; var<=endvalue; var=var+increment)
 
      {
 
      //code to be executed
 
      }
 
   

The while Loop

If you don't know the exact number of times your code is supposed to execute, use a while loop.

With a while loop your code executes while a given condition is true; as soon as this condition evaluates to false, the while loop stops.

Here's its basic structure:

 
   //loop while initial value is less than or equal to end value
 
   //Take note: if the condition evaluates to false from the start,
 
   //the code will never be executed
 
   while (variable <= endvalue)
 
      {
 
      //code to be executed
 
      }
 
   

do ... while Loop

This kind of loop is similar to the while loop. The difference between the two is this:

In the case of the while loop, if the test condition is false from the start, the code in the loop will never be executed.

In the case of the do ... while loop, the test condition is evaluated after the loop has performed the first cycle. Therefore, even if the test condition is false, the code in the loop will execute once.

Here's the basic structure of a do ... while loop:
 
   //the command is given before the test condition is checked
 
   do
 
   {
 
   //code to be executed
 
   }
 
   //condition is evaluated at this point:
 
   //if it's false the loop stops here
 
   while (variable <= endvalue)
  
   

Try out: add random number of images with a for loop

Time to get coding: prepare a fresh HTML document with a div tag and an id of "wrapper" and add the following JavaScript magic:

 
   <!DOCTYPE html>
   <html>
   <head>
   <title>Lesson 7: Leave Boring Repetitive Stuff to JavaScript with Loops</title>
   </head>
   <body>
   <h1>Lesson 7: for Loop</h1>
 
   <div id="wrapper"></div>
   
   <script type="text/javascript">
 
   //Grab the html div by its id attribute
 
   //and store it in a var named container
 
   var container = document.getElementById("wrapper");
 
   //use Math.random to generate a random number
 
   //between 0 and 1. Store random number in a var
 
   var randomNumber = Math.random();
 
   //use Math.floor() to round off the random number
 
   //to an integer value between 0 and 10 and store it in a var
 
   var numImages = Math.floor(randomNumber * 11);
 
   //just for testing purposes, lets alert the resulting random number
 
   alert(numImages);
 
   //the loop will run for the number of times indicated
 
   //by the resulting random number
 
   for (var i=1; i <= numImages; i++)
 
   {
 
   //code to be executed:
 
   //create a var and store a string made of a new HTML img element
 
   //and the iteration variable i (use + concatenation operator):
 
   //i contains the iteration number
 
   //Take note:make sure the img src corresponds to a real image file
 
   var newImage = '<img src="loop.gif" alt="#" />' + i;
 
   //use the container var that stores the div element
 
   //and use innerHTML to insert the string stored in the newImage var
 
   //Use shortcut assignment += so previous values do not get wiped off
 
   container.innerHTML += newImage;
 
   }
 
   </script>
  
   </body>
   </html>
 
   

Comments

Popular posts from this blog

TOP PHP freamwork

What is required for it startup company ?

Place background image in CSS