HTML and CSS Reference
In-Depth Information
and the second one as: Is the current value of the variable course the same as the string "Programming
Games"?
The comparison example is easy to understand; we use > to check if one value is greater than another,
and < to check the opposite. The value of the expression will be one of the two logical values true or
false .
The second expression is probably a little more confusing. You may be wondering about the two equal
signs and maybe also the quotation marks .The comparison operator in JavaScript (and several other
programming languages) that checks for equality is this combination of two equal signs. We need two
equal signs because the single equal sign is used in assignment statements and it can't do double duty. If
we had written course = "Programming Games" , we would have been assigning the value
"Programming Games" to our course variable rather than comparing the two items. The quotation marks
define a string of characters, starting with P, including the space, and ending with s.
With that under our belts, we can now take a look at how to write code that does something only if a
condition is true.
if (condition) {
code
}
If we want our code to do one thing if a condition is true and another thing if it is NOT true, the format is:
if (condition) {
if true code
}
else {
if not true code
}
Note that I used italics here because this is what is called pseudo-code, not real JavaScript that we would
include in our HTML document.
Here are some real code examples. They make use of alert , a built-in function that causes a small
window with the message indicated by the argument given between the parentheses to pop up in the
browser. The user must click OK to continue.
if (temp>85) {
alert("It is hot!");
}
if (age > 21) {
alert("You are old enough to buy a drink.");
}
else {
alert("You are too young to be served in a bar.");
}
We could write the craps application using just if statements. However, JavaScript supplies another
construct that makes things easier—the switch statement. The general format is:
switch(x) {
case a:
 
Search WWH ::




Custom Search