HTMLisEasy.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 type="text/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 in that for statement...

  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 succeeding curly brackets once. If x is NOT less than 5, end the loop.

  3. for ( x = 0; x < 5; x++ ) -- assuming x is less than 5, increment x by one and loop back 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: Using the for statement, 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 >>
Javascript Tutor
Lessons: Intro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Javascript Authoring Guide      JavaScript FAQ
HTML 4.0 Reference      Google Groups (Advanced Search)