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...

for ( x = 0; x < 5; x++ ) - x starts at 0

for ( x = 0; x < 5; x++ ) - if x is less than 5, execute the instructions in the brackets once... alert(x);

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?

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


  Next>>  
 
Lesson 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