Elvis operator


In certain computer programming languages, the Elvis?? operator, often written ?:, or or ||, is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. The Elvis operator is a variant of the ternary conditional operator, in the sense that the expression with the Elvis operator A ?: B is approximately equivalent to the expression with the ternary operator A ? A : B.
Some computer programming languages have different semantics for the ?? operator: instead of the first operand having to result in a boolean, it must result in an object reference. If the resulting object reference is not null, it is returned. Otherwise the value of the second operand is returned. This distinction is necessary because in C#, references are not implicitly convertible to a boolean.
The name "Elvis operator" refers to the fact that when its common notation, ?:, is viewed sideways, it resembles an emoticon of Elvis Presley with his quiff.

Example

Boolean variant

In a language that supports the Elvis operator, something like this:
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 example, using the :
except that it does not evaluate the f twice if it is true.

Object reference variant

This code will result in a reference to an object that is guaranteed to not be null. Function f returns an object reference instead of a boolean, and may return null:

Languages supporting the Elvis operator

In several languages, such as Common Lisp, Clojure, Lua, Perl, Python, Ruby, and JavaScript, the OR operator 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. When the left hand side is true, the right hand side is not even evaluated; it is "short-circuited."