Elvis operator

This article is about the use of the ?: operator as a binary operator. For use as a ternary operator, see ?:.

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true, and otherwise evaluates and returns its second operand. It is a variant of the ternary conditional operator, ? :, found in those languages (and many others): the Elvis operator is the ternary operator with its second operand omitted.

Example

In a language that supports the Elvis operator, something like this:

x = f() ?: g()

will set x equal to the result of f() if that result is a true value, and to the result of g() otherwise.

It is equivalent to this:

x = f() ? f() : g()

except that it does not evaluate the f() twice if it is true.

Name

The name "Elvis operator" refers to its resemblance to an emoticon of Elvis Presley.[1][2]

Languages supporting the Elvis operator

Analogous use of the OR operator

In several languages, such as Perl, Python, and JavaScript, the OR operator (typically || or or) has the same behavior as the above: returning its first operand if it would evaluate to true in a boolean environment, and otherwise evaluating and returning its second operand.

Comparison to the null coalescing operator

While Elvis operator compares to boolean false, Null coalescing operator compares to null.

See also

References

This article is issued from Wikipedia - version of the 11/10/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.