Elvis operator

Last updated

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.

Contents

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] .

Alternative syntaxes

In several languages, such as Common Lisp, Clojure, Lua, Object Pascal, Perl, Python, Ruby, and JavaScript, the OR operator (typically || or or) has the same behavior as the above: returning its first operand if it would evaluate to a truthy value, and otherwise evaluating and returning its second operand, which may be a truthy or falsy value. When the left-hand side is truthy, the right-hand side is not even evaluated; it is "short-circuited". This is different than the behavior in other languages such as C/C++, where the result of || will always be a (proper) boolean.

Example

Boolean variant

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 truthy, and to the result of g() otherwise.

It is equivalent to this example, using the conditional ternary operator:

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

except that it does not evaluate f() twice if it yields truthy. Note the possibility of arbitrary behaviour if f() is not a state-independent function that always returns the same result.

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, which is universally regarded as falsy:

x = f() ?: "default value"

Languages supporting the Elvis operator

See also

Related Research Articles

In logic, mathematics, and computer science, arity is the number of arguments or operands taken by a function, operation or relation. In mathematics, arity may also be called rank, but this word can have many other meanings. In logic and philosophy, arity may also be called adicity and degree. In linguistics, it is usually named valency.

GNU Bison, commonly known as Bison, is a parser generator that is part of the GNU Project. Bison reads a specification in Bison syntax, warns about any parsing ambiguities, and generates a parser that reads sequences of tokens and decides whether the sequence conforms to the syntax specified by the grammar.

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined Boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition . Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime. Conditional statements are the checkpoints in the programme that determines behaviour according to situation.

This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, ternary if, or inline if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is by far and large the most common, but alternative syntaxes do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.

In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.

In computer science, the Boolean is a data type that has one of two possible values which is intended to represent the two truth values of logic and Boolean algebra. It is named after George Boole, who first defined an algebraic system of logic in the mid 19th century. The Boolean data type is primarily associated with conditional statements, which allow different actions by changing control flow depending on whether a programmer-specified Boolean condition evaluates to true or false. It is a special case of a more general logical data type—logic does not always need to be Boolean.

In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality and inequalities.

In computer science, a Boolean expression is an expression used in programming languages that produces a Boolean value when evaluated. A Boolean value is either true or false. A Boolean expression may be composed of a combination of the Boolean constants true or false, Boolean-typed variables, Boolean-valued operators, and Boolean-valued functions.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

In computing, IIf is a function in several editions of the Visual Basic programming language and ColdFusion Markup Language (CFML), and on spreadsheets that returns the second or third parameter based on the evaluation of the first parameter. It is an example of a conditional expression, which is similar to a conditional statement.

The conditional operator is supported in many programming languages. This term usually refers to ?: as in C, C++, C#, and JavaScript. However, in Java, this term can also refer to && and ||.

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type. In statically typed languages, a nullable type is an option type, while in dynamically typed languages, equivalent behavior is provided by having a single null value.

In computer science, a three-way comparison takes two values A and B belonging to a type with a total order and determines whether A < B, A = B, or A > B in a single operation, in accordance with the mathematical law of trichotomy.

The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, such as : C# since version 2.0, Dart since version 1.12.0, PHP since version 7.0.0., Perl since version 5.10 as logical defined-or, PowerShell since 7.0.0, and Swift as nil-coalescing operator.

In computer programming, ellipsis notation is used to denote ranges, an unspecified number of arguments, or a parent directory. Most programming languages require the ellipsis to be written as a series of periods; a single (Unicode) ellipsis character cannot be used.

In programming jargon, Yoda conditions is a programming style where the two parts of an expression are reversed from the typical order in a conditional statement. A Yoda condition places the constant portion of the expression on the left side of the conditional statement.

Kotlin is a cross-platform, statically typed, general-purpose high-level programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin's standard library depends on the Java Class Library, but type inference allows its syntax to be more concise. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code via LLVM. Language development costs are borne by JetBrains, while the Kotlin Foundation protects the Kotlin trademark.

In object-oriented programming, the safe navigation operator is a binary operator that returns null if its first argument is null; otherwise it performs a dereferencing operation as specified by the second argument.

References

  1. Joyce Farrell (7 February 2013). Java Programming. p. 276. ISBN   978-1285081953. 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.
  2. "?? Operator". C# Reference. Microsoft. Retrieved 5 December 2018.
  3. "Conditional expressions". Dart Language. Google.
  4. "perlop - Perl operators and precedence -Perldoc Browser". Perl.org. Retrieved 2023-01-19.
  5. "Using the GNU Compiler Collection (GCC): Conditionals with omitted operands". gcc.gnu.org.
  6. "Using and Porting the GNU Compiler Collection (GCC): C Extensions". gcc.gnu.org.
  7. "Elvis Operator (?: )".
  8. "The Apache Groovy programming language - Groovy 1.5 release notes". groovy-lang.org.
  9. "PHP: Comparison Operators - Manual". PHP website. Retrieved 2014-02-17.
  10. "Null Safety - Kotlin Programming Language". Kotlin.
  11. Albahari, Joseph; Albahari, Ben (2015). C# 6.0 in a Nutshell (6 ed.). O'Reilly Media. p. 59. ISBN   978-1491927069.
  12. Efftinge, Sven. "Xtend - Expressions". eclipse.org.
  13. "Closure Templates - Expressions". GitHub. 29 October 2021.
  14. "Elvis Operator - Ballerina Programming Language". Ballerina. Archived from the original on 2018-12-20. Retrieved 2018-12-19.
  15. "Nullish coalescing operator (??) - JavaScript | MDN". developer.mozilla.org. Retrieved 2023-01-05.