
Home
|
 
JAVA SCRIPT
Examples
of a single If-Then Statement
|
|
If you typed yes in the prompt box, you should have
received a warm greeting before seeing the rest of the page. If
you typed something else, you shouldn't have gotten this greeting.
Here's the the heart of the script:
|
var monkey_love = prompt("Do you love the monkey?","Type yes or no");
if (monkey_love == "yes")
{
alert("Welcome! I'm so glad you came! Please, read on!");
}
| You've
seen the first line before. It just brings up a prompt box and
loads the user's response into the variable monkey_love.
The second line, however, has something new in it: a condition.
This condition says that if the variable monkey_love
equals the value "yes," the script should run the
statement between the curly brackets. If monkey_love
equals something else, the statement will not be run.
Note that the condition is two equal signs. This is one
of those things that everyone messes up initially. If you put one
equal sign instead of two, you're telling JavaScript that monkey_love
should equal "yes" instead of testing whether or
not it actually does equal "yes." Luckily, most
browsers look for this sort of mistake and will warn you about it
when you try to run your script. However, it's best not to make
the mistake in the first place.
Other typical conditions are:
|
(variable_1 > variable_2) is true if variable_1 is greater than variable_2
(variable_1 < variable_2) is true if variable_1 is less than variable_2
(variable_2 <= variable_2) is true if variable_1 is less than or equal to variable_2
(variable_1 != variable_2) is true if variable_1 does not equal variable_2
|
Two ways to make your conditions fancier:
If you want two things to be true before running the statements
in the curly brackets, you can do this:
|
if ((variable_1 > 18) && (variable_1 < 21))
{
document.writeln(variable_1 + "can vote, but can't drink.");
}
|
Notice the two ampersands. That's how you say "and"
in JavaScript. Notice also that the whole clause, including the
two sub-parts and the ampersands must be enclosed in parentheses.
If you want either one of two things to be true before running
the statements in the curly brackets, do this:
|
if ((variable_1 == "bananas") || (variable_1 == "JavaScript"))
{
document.writeln("The monkey is happy because it has " + variable_1);
}

 |