Javascript Tutor - Lesson 19

## The for statement.

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

```<html>
<title></title>

<script type="text/javascript">

function boxPopper()
{
for (var x = 0; x < 5; x++)
{
}
}

</script>

<body>

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