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.