pagetutor.com - HTML tutorials for the rest of us

Javascript Tutor - Lesson 19

The for statement.

The for statement is a very useful tool. Here is an example...


<HTML>

<HEAD>

<TITLE></TITLE>



<SCRIPT language="Javascript"><!--



function boxPopper()

{

   for (var x = 0; x < 5; x++)

   {

      alert(x);

   }

}



//--></SCRIPT>



</HEAD>

<BODY>



<A HREF="javascript:boxPopper()">Click here</A>



</BODY>

</HTML>

Try it.

Here's what's happening...

  1. for ( x = 0; x < 5; x++ ) - x starts at 0
  2. for ( x = 0; x < 5; x++ ) - if x is less than 5, execute the instructions in the brackets once... alert(x);
  3. for ( x = 0; x < 5; x++ ) - increment x by one and go to step 2

The loop stops when x is no longer less than 5. (You might be thinking... hey, the loop stopped after 4! To which I ask you... is 5 less than 5? If you say yes, keep thinking about it until you say no ;-)

Exercise: Come up with a script that calculates the square root of each integer from 0 to 20, rounds each to one decimal point and displays them in an alert box like so...


The square root of 0 is 0

The square root of 1 is 1

The square root of 2 is 1.4

etc...

Hint: you can specify a line break in an alert box with an escaped n (n for newline) - \n...

alert("Hand\nhand\nfingers\nthumb"); - try it

Again, it's a tough one. Hey, if they were easy you wouldn't learn anything, right?

Here is a solution.

Exercise: Make a slight alteration to that last exercise and have it round to two decimal places.

Here is a solution.

<< BACK         NEXT >>
pagetutor.com



Invest in the future - Hug your kid today.