In certain computer programming languages, the Elvis operator, often written ?:
, is a binary operator that returns the evaluated first operand if that operand evaluates to a value likened to logically true (according to a language-dependent convention, in other words, a truthy value), and otherwise returns the evaluated second operand (in which case the first operand evaluated to a value likened to logically false, in other words, a falsy value). This is identical to a short-circuit or with "last value" semantics. The notation of the Elvis operator was inspired by the ternary conditional operator, ? :
, since the Elvis operator expression A ?: B
is approximately equivalent to the ternary conditional expression A ? A : B
.
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 signature hairstyle.[1]
A similar operator is the null coalescing operator, where the boolean truth(iness) check is replaced with a check for non-null instead. This is usually written ??
, and can be seen in languages like C#[2] or Dart.[3]
The new operator is called Elvis operator because it uses a question mark and a colon together (?:); if you view it sideways, it reminds you of Elvis Presley.