14.07.2013 Views

Essentials of Javascript - Cultural View

Essentials of Javascript - Cultural View

Essentials of Javascript - Cultural View

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

?: 52<br />

?:<br />

In computer programming, ?: is a ternary operator that is part <strong>of</strong> the syntax for a basic conditional expression in<br />

several programming languages. It is commonly referred to as the conditional operator.<br />

It originally comes from BCPL, whose equivalent syntax for e1 ? e2 : e3 was e1 -> e2, e3 [1] . Languages derived<br />

from BCPL tend to feature this operator.<br />

Conditional assignment<br />

?: is used as follows:<br />

condition ? value if true : value if false<br />

The condition is evaluated true or false as a Boolean expression. On the basis <strong>of</strong> the evaluation <strong>of</strong> the Boolean<br />

condition, the entire expression returns value if true if condition is true, but value if false otherwise. Usually the two<br />

sub-expressions value if true and value if false must have the same type, which determines the type <strong>of</strong> the whole<br />

expression. The importance <strong>of</strong> this type-checking lies in the operator's most common use—in conditional assignment<br />

statements. In this usage it appears as an expression on the right side <strong>of</strong> an assignment statement, as follows:<br />

variable = condition ? value if true : value if false<br />

The ?: operator is similar to the way conditional expressions (if-then-else constructs) work in functional<br />

programming languages, like Scheme, ML, and Haskell, since if-then-else forms an expression instead <strong>of</strong> a statement<br />

in those languages.<br />

Usage<br />

This ternary operator's most common usage is to make a terse simple conditional assignment statement. For example,<br />

if we wish to implement some C code to change a shop's opening hours to 12 o'clock in weekends, and 9 o'clock on<br />

weekdays, we may use<br />

int opening_time = (day == WEEKEND) ? 12 : 9;<br />

instead <strong>of</strong> the more verbose<br />

int opening_time;<br />

if (day == WEEKEND)<br />

else<br />

opening_time = 12;<br />

opening_time = 9;<br />

The two forms are nearly equivalent. Keep in mind that the ?: is an expression and if-then-else is a statement. Note<br />

that neither value if true nor value if false expressions can be omitted from the ternary operator without an error<br />

report upon parsing. This contrasts with if..else statements, where the else clause can be omitted.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!