Miscellaneous Operators

JavaScript supports a number of other miscellaneous operators, described in the following sections.

The Conditional Operator (?:)

The conditional operator is the only ternary operator (three operands) in JavaScript and is sometimes actually called the ternary operator. This operator is sometimes written ?:, although it does not appear quite that way in code. Because this operator has three operands, the first goes before the ?, the second goes between the ? and the :, and the third goes after the :. It is used like this:

x > 0 ? x*y : -x*y

The first operand of the conditional operator must be (or be convertable to) a boolean value -- usually this is the result of a comparison expression. The second and third operands may have any value. The value returned by the conditional operator depends on the boolean value of the first operand. If that operand is true, the value of the conditional expression is the value of the second operand. If the first operand is false, the value of the conditional expression is the value of the third operand.

While you can achieve similar results using the if statement, the ?: operator often provides a handy shortcut. Here is a typical usage, which checks to be sure that a variable is defined, uses it if so, and provides a default value if not:

greeting = "hello " + (username != null ? username : "there");

This is equivalent to, but more compact than, the following if statement:

greeting = "hello "; if (username != null) greeting ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.