Lesson 7: Leave Boring Repetitive Stuff to JavaScript with loops

By Maria Antonietta Perna

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>
	
	  

Prepare a graphic file and store it in the same directory as your document, save your work, run the page in the browser and keep reloading it: the alert box will display a random number each time, then an img element is dynamically added to the web page as many times as indicated by the random number.

Questions, questions, questions

I know, there's a lot to ask about the code sample above. More specifically: 1) What's this document.getElementById(element Id)? 2) What are Math.random() and Math.floor(number)? And finally, 3) what's innerHTML? Let's tackle each question in turn:

  1. Get hold of HTML elements with document.getElementById(element Id)

    JavaScript can perform all sorts of magic on any HTML element once it gets hold of it. This can be done in more than one way. However, the most straightforward way is by using the document.getElementById(element Id) command. The JavaScript interpreter reads it as follows:

    "Hey browser, find the HTML element with the id name like the one in brackets."

    Because JavaScript usually does something with the element, this gets conveniently stored inside a variable. What you did in the sample code above was to grab hold of the div with the id attribute named wrapper and store it in a variable named container.

  2. Generate random numbers with Math.random() and Math.floor(number)

    JavaScript has built-in commands to perform complex mathematical operations quickly and easily.

    Math.random() generates a random number between 0 and 1. Try it out on your own by typing var randomNum = Math.random(); alert(randomNum); inside a <script> tag.

    Math.floor(number) rounds a number downwards to the nearest integer, and returns the result. The JavaScript interpreter reads it as follows:

    "Hey browser, take the number in brackets and round it down to the nearest integer number."

    Try it out on your own by typing var roundedNumber = Math.floor(6.2); alert(roundedNumber); inside a <script> tag. Keep changing the number in brackets and see how JavaScript returns the corresponding integer number.

    In the previous example, you used Math.floor() together with Math.random(number) to generate a random integer number between 0 and 10 (you typed 11 rather than 10 because the round number returned by Math.random() starts at 0 not 1).

  3. Add new mark-up inside HTML elements with innerHTML

    A JavaScript script can make HTML elements appear and disappear, change place or color, and much more.

    There's more than one way to add new mark-up in your HTML document, but using innerHTML makes it very easy and straightforward. The JavaScript interpreter reads the command as follows:

    "Hey browser, take the string to the right of the assignment operator and insert it into the HTML mark-up."

    What you did in the sample code above was to take the variable storing the wrapper div element and applying innerHTML to it to insert an img tag inside the div.

Try out: add images to the page with a while loop

Use the same HTML document from the previous example, but delete all the JavaScript between the <script> ... </script> tags. Now, type in the following JavaScript code:

	
	  <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");
	
	  //create the var containing the counter
	
	  //and give it an initial value of 0
	
	  var numImages = 0;
	
	  //start the loop: while the number of images is less than or
	
	  //equal to 10 (loop starts at 0 not 1, so type 9 not 10),
	
	  //keep cycling and increase the counter by 1
	
	  while (numImages <= 9)
	
	  {
	
	  //this is the block of code to be executed:
	
	  //build the string to insert in the HTML document
	
	  //and store it in the newImage var
	
	  //Take note:make sure the img src corresponds to a real image file
	
	  var newImage = '<img src="loop.gif" alt="#" />' + numImages;
		
	  //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;
	
	  //increase the counter by 1 using the increment operator
	
	  numImages ++;
	
	  }
	
	  </script>
	
	  

Make sure the image file is in place, save your work and run the page in the browser. You should see something similar to the example page indicated in the link above.

Run a while loop with a false condition

Now make just a small change to the code above: replace var numImages = 0; with var numImages = 12;. Now the initial condition is false from the start: the counter is a number greater than 10.

Save your work, run the page and see what happens. If all works fine, nothing at all should happen: the loop doesn't even get started.

Try out: add images to the page with a do ... while loop

Use the same HTML document as the previous example. Also, the JavaScript code is very similar to the previous example: simply move the while (condition) outside the action block and type do in its place, like the example below:

	
	  <script type="text/javascript">
	
	  var container = document.getElementById("wrapper");
	
	  var numImages = 0;
	
	  do
	
	  {
	
	  //this block gets executed first:
	
	  var newImage = '<img src="loop.gif" alt="#" />' + newImage;
	
	  container.innerHTML += newImage;
	
	  numImages ++;
	
	  }
	
	  //here's the condition to evaluate:
	
	  //the first cycle has already executed.
	
	  while (numImages <= 9);
	
	  </script>
	
	  

Save your work and run the page in the browser. You should see something similar to the example page indicated in the link above.

Run a do ... while loop with a false condition

Make just a small change to the code above: once again, replace var numImages = 0; with var numImages = 12;. Now the initial condition is false from the start: the counter is a number greater than 10.

Save your work, run the page and see what happens. Unlike what happened with the while loop, now you should see one image displayed on the web page: the loop has completed the first cycle and only afterwards the test condition is evaluated. In this instance the condition is false and the loop stops after the first iteration completes.

Summary

That's all for this lesson. Your JavaScript toolbox is getting richer and richer: you can write repetitive code with loops, manipulate HTML content dynamically, and write scripts that generate random numbers.

Pat yourself on the back and take a well deserved break before moving on to the next big topic: functions.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 6: Even Smarter Scripts with if…else and switch

Lesson 8: Package your JavaScript Code with Functions >>