Null coalescing operator

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 (in alphabetical order): C#[1] since version 2.0,[2] Dart[3] since version 1.12.0,[4] PHP since version 7.0.0,[5] Perl since version 5.10 as logical defined-or,[6] PowerShell since 7.0.0,[7] and Swift[8] as nil-coalescing operator.

While its behavior differs between implementations, the null coalescing operator generally returns the result of its left-most operand if it exists and is not null, and otherwise returns the right-most operand. This behavior allows a default value to be defined for cases where a more specific value is not available.

In contrast to the ternary conditional if operator used as x ? x : y, but like the binary Elvis operator used as x ?: y, the null coalescing operator is a binary operator and thus evaluates its operands at most once, which is significant if the evaluation of x has side-effects.

  1. ^ "?? and ??= operators - the null-coalescing operators". Microsoft Learn. 2023-07-27.
  2. ^ "ECMA-334, 3rd edition, June 2005" (PDF). ecma-international.org. Ecma International. June 2005. p. 63.
  3. ^ "Conditional expression". Dart.
  4. ^ "Dart SDK Changelog, 1.12.0". GitHub. 2015-08-31.
  5. ^ "PHP 7.0.0 Released". PHP. 2015-11-12.
  6. ^ "perlop - Perl expressions: operators, precedence, string literals". Perldoc Browser.
  7. ^ "PowerShell 7 Preview 5". PowerShell. 2019-10-23. Retrieved 2020-02-15.
  8. ^ "The Swift Programming Language (Swift 5): Basic Operators: Nil-Coalescing Operator". docs.swift.org.