Simple if - else 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 heart of the script:

var loveMe = prompt("Do you love me?", "yes");

if (loveMe.toLowerCase() == "yes") alert("Welcome! I'm so glad! Please, read on!");
else alert("I'm sad!");

See the script in action.

You've seen the first line before. It just brings up a prompt box and loads the user's response into the variable loveMe. The second line, however, has something new in it: a condition. This condition says that if the variable loveMe equals the value "yes," the script should run the statement. If loveMe equals something else, the statement will not be run.

NOTE: that the condition is two equal signs (==) - we are making a comparison and not assignment here. 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 loveMe 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:

(var1 > var2)  is true if var1 is greater than var2

(var1 < var2)  is true if var1 is less than var2

(var2 <= var2)  is true if var1 is less than or equal to var2

(var1 != var2)  is true if var1 does not equal to var2

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 ((var1 > 18) && (var1 < 21)) {
     document.write(var1 +  "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 ((var1 == "love") || (var1 == "need")) {
     document.write("I'm happy because you " +  var1 + " me");
}