Do you find yourself using numerous if/else statements in JavaScript similar to this one?
Code:
if (userid === 2) {
myName = "John";
}
else {
myName = "Someone Else";
}
The code (assuming the variables have been defined) simply assigns a different value to the
myName variable depending on a condition: whether the
userid is strictly equal to 2 or not (meaning it has to be equal and of the same type to be true). With this type of simple if/else statement, JavaScript offers a way to shorten this to a single line of code by using what is called the ternary operator. Here is how it works:
Code:
variable_name = (condition) ? value_if_true : value_if_false;
Basically, it assigns a value to a variable based on the result of a conditional statement (in parentheses above). The value after the question mark is assigned if the condition returns true, while the value after the colon is assigned if the condition returns false.
If we use this to rewrite our example code from above, the code would now look like this:
Code:
myName = (userid === 2) ? "John" : "Someone Else";
Here, "John" is assigned to
myName if the condition returns true, and "Someone Else" is assigned if the condition returns false.
This employs a simple assignment statement format, avoiding the use if/else blocks.
Give it a try — it may help you shorten your scripts!
-----------------------------------------------------------------
John Pollock is an author a Web developer who contributes to
Web Xpertz and writes for his own site,
Script the Web.
-----------------------------------------------------------------