HTML and CSS Reference
In-Depth Information
You can also define code that should run if the condition evaluates to
false
. This is done by placing the
else
keyword after the closing curly brace of the
if
statement and then placing the code within two new curly braces.
This is shown in the following example.
if(a < b) {
document.write(“a is smaller than b!");
} else {
document.write(“a is not smaller than b!");
}
This sort of control structure is useful when writing computer programs in any programming language. In later
chapters you will be using
if
and
else
statements to check whether a user's web browser supports new technolo-
gies like GeoLocation, LocalStorage, and Canvas.
Looping
When coding, you will find that you need to repeat a task multiple times. An example use case would be if you had a
collection of structured data about 100 users. The task is to display that data on the page, once for each user. Now
you certainly don't want to write out the same code 100 times. This is where loop structures come in. Using them to
repeat an action a set number of times can greatly decrease the amount of code you have to write.
There are two types of loop structures,
for
loops and
while
loops. In this section, you learn how to use these in
your programs and when you should use one instead of the other.
For Loops
For
loops are used when you have a set number of times that you want to execute some code. A
for
loop has three
parameters.
The
initialization
parameter comes first. This is usually used to create a counter variable that can track how many
times the
for
loop has executed.
Next up is the
condition
. This will be evaluated before each iteration of the loop and should evaluate to either
true
or
false
, just like conditions in
if
statements. It is commonly used to check whether the counter is within a de-
sired range.
The final parameter is the
final-expression
. This expression is executed after each iteration of the loop. This typically
is used to increase the value of the counter variable by one.
Let's write a little program that uses a
for
loop:
1.
Create a new file in your text editor.
2.
Save this file as
example10-7.js
.
3.
Add the following code to this file.
window.onload = function() {
for( var i = 0; i < 5; i++ ) {
document.write(i + '<br>');
}
}
4.
Save the
example10-7.js
file.