HTML and CSS Reference
In-Depth Information
var count = 10;
var sum = 100;
var average = sum/count;
Control Structures
To get your scripts to actually do something, you'll need control structures, which come
in two main varieties. There are conditional statements, which are used to make deci-
sions, and loops, which enable you to repeat the same statements more than once.
The if Statement
The main conditional statement you'll use is the if statement. The statements inside an
if statement are only executed if the condition in the if statement is true. If you were
writing code in English rather than JavaScript, an if statement would read like this: “If
the background of this element is blue, turn it red.” There's also an else clause associ-
ated with if . The statements in the else clause are executed if the if statement's condi-
tion is false. An if statement with an else clause reads like this: “If the background of
this element is blue, turn it red; otherwise, turn it blue.”
Let's look at a simple example:
var color = “red”;
if (color == “blue”) {
color == “red”;
} else {
color == “blue”;
In this example, I've created a variable named color and use that in my if statement.
Later, I explain how to retrieve information from the page, style sheets, and form ele-
ments and use them in your JavaScript code. For now, it's easier to explain with hard-
coded values. The statement begins with the if keyword, followed by the condition
enclosed within parentheses. The statements to be executed if the condition is true are
placed within curly braces. In this case, I've also included an else clause. The statement
associated with it is also enclosed in curly braces. Finally, let's look at the condition. It is
true if the variable color is equal to the value “blue” . In this case, the condition is false,
so the else clause will be executed.
The == operator tests for equality, and is but one of several conditional operators avail-
able in JavaScript. Table 14.3 contains all the conditional operators.
Search WWH ::

Custom Search