Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

The JavaScript Language 483

17


Let’s look at a simple example, which will work in the Console:


var colo r = "red";
if (color == "blue") {
color = "red";
} else {
color = "blue";
}
color;


In this example, I’ve created a variable named color and use that in my if statement.
Later, I’ll explain how to retrieve information from the page, style sheets, and form ele-
ments in your JavaScript code and make changes to them. For now, it’s easier to explain
the conditional statements 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 available
in JavaScript. Table 17.3 contains all the conditional operators.


TABLE 17.3 JavaScript Comparison Operators


Operator Operator Description Notes


== Equal to a == b tests to see whether a equals b.


!= Not equal to a != b tests to see whether a does not equal b.


< Less than a < b tests to see whether a is less than b.


<= Less than or equal to -a <= b tests to see whether a is less than or equal
to b.



= Greater than or equal to -a >= b tests to see whether a is greater than or
equal to b.




Greater than a > b tests to see whether a is greater than b.



You can also enter conditional expressions in the Console to see their results. As you’ll
see, they all return either true or false. For example, 1 == 2 will evaluate as false, and
5 > 3 will evaluate as true. If you’re curious about the result of a conditional expres-
sion, you can always test it there.

Free download pdf