Page 3
An If-Then-Else Shortcut
One of the most commonly used statements in JavaScript is the good old
if-then-else. Take the reward schedule for instance:
if (monkey_behavior == "good")
{
var toy = "videogames";
} else {
var toy = "rocks";
}
In plain English, this means, "If the monkey's been good, he gets to play videogames. If not, he gets only rocks." For reasons of legibility, it is a perfectly good way to do this. For those who don't like to squander keystrokes, however, there is a shortcut (albeit, a less legible one). It's called the "conditional operator," and it goes a little something like this:
var toy = (monkey_behavior=="good") ? "videogames" : "rocks";
This expression does the same thing as the if-then-else statement
above it. See what I mean about legibility?
The conditional operator has three parts: a conditional test,
a value to return if that test is true, and a value to return if that
test is false. So, in the above example, the conditional test is
(monkey_behavior=="good"). If that test is true, it returns the value after the question mark. In this case, it's the string videogames. If the conditional test is false, the value after the colon is returned; in this case, it's rocks.
This sort of shortcut is most useful inside function calls. For
example, you can use it to do something like this:
var password = "open sesame";
var answer = prompt("what's the password? ","");
alert((answer == password) ? "welcome!" : "buzz off");
Click here to see this in action. What you're seeing is the conditional operator doing
its job and returning either welcome or buzz off, depending on the
answer you give at the prompt. The value returned by the
conditional gets sent to alert, which throws up an alert box with
that value.
Without the conditional operator, the code would look like this:
var password = "open sesame";
var answer = prompt("what's the password? ","");
if (answer == password)
{
alert("welcome");
} else {
alert("buzz off");
}
It's definitely longer, but some people find it more readable, and understandable,
to actually write out the if-then-else statement.
The method you choose is simply a matter of personal preference.
OK, last stop on today's tour of loose ends: the mysterious var.