HTML and CSS Reference
In-Depth Information
5.
Create a new HTML file called
example10-7.html
.
6.
Copy the following code into this file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>For Loops</title>
</head>
<body>
<script src="example10-7.js"></script>
</body>
</html>
7.
Save this file.
Here you have first initialized a counter variable
i
and given it the value
0
.
The condition then states that this loop should continue to execute for as long as the counter variable
i
is less than 5.
Finally, you declare that after each iteration of this loop, the counter variable should be increased by one. The
++
syntax here is simply a shorthand way of writing
i=i+1
.
If you run this example in your browser, you should see the following:
0
1
2
3
4
Notice that the output starts from 0. This is because you initialized the counter variable at 0. In programming, you al-
most always start counting from 0. This can sometimes lead to the infamous
off-by-one
bug, so be careful to check
your numbers if your output is slightly off.
While Loops
While
loops are similar to
for
loops; however,
while
loops can be used when you don't know how many times
you want the loop to iterate. A
while
loop takes only one parameter, the condition. It will keep iterating until this
condition evaluates to true. You want to be sure that it will evaluate to
true
at some point; otherwise, it will keep
iterating until the end of time, or your computer dies, whichever comes first. This is known as an
infinite
loop.
Let's have a bit more fun with
while
loops. It's time to create a little guessing game. As always, the code below
can be found on the topic's website in the Chapter 10 folder.
1.
Create a new file in your text editor called
example10-8.js
.
2.
Add the following code to this new file:
window.onload = function() {
// Generate random number between 0 and 10.
var randomNumber = Math.floor(Math.random()*10);
// Initialize a variable for the guess.
var guess;