The null coalescing operator (called the Logical Defined-Or operator in
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
) is a
binary operator
In mathematics, a binary operation or dyadic operation is a rule for combining two elements (called operands) to produce another element. More formally, a binary operation is an operation of arity two.
More specifically, an internal binary op ...
that is part of the syntax for a basic
conditional expression in several
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
s, including
C#,
PowerShell
PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sou ...
as of version 7.0.0,
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
as of version 5.10,
Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIFT ...
, and
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
7.0.0. 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
Null may refer to:
Science, technology, and mathematics Computing
*Null (SQL) (or NULL), a special marker and keyword in SQL indicating that something has no value
*Null character, the zero-valued ASCII character, also designated by , often used ...
, 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
In certain computer programming languages, the Elvis operator, often written ?:, 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. This is ident ...
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
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
.
Examples by languages
Bourne-like Shells
In
Bourne shell
The Bourne shell (sh) is a shell command-line interpreter for computer operating systems.
The Bourne shell was the default shell for Version 7 Unix. Unix-like systems continue to have /bin/sh—which will be the Bourne shell, or a symbolic link ...
(and derivatives), "If ''parameter'' is unset or null, the expansion of ''word'' is substituted. Otherwise, the value of ''parameter'' is substituted":
#supplied_title='supplied title' # Uncomment this line to use the supplied title
title=$
echo "$title" # prints: Default title
C#
In
C#, the null coalescing operator is
??
.
It is most often used to simplify expressions as follows:
possiblyNullValue ?? valueIfNull
For example, if one wishes to implement some C# code to give a page a default title if none is present, one may use the following statement:
string pageTitle = suppliedTitle ?? "Default Title";
instead of the more verbose
string pageTitle = (suppliedTitle != null) ? suppliedTitle : "Default Title";
or
string pageTitle;
if (suppliedTitle != null)
else
The three forms result in the same value being stored into the variable named
pageTitle
.
Note that
suppliedTitle
is referenced only once when using the
??
operator, and twice in the other two code examples.
The operator can also be used multiple times in the same expression:
return some_Value ?? some_Value2 ?? some_Value3;
Once a non-null value is assigned to number, or it reaches the final value (which may or may not be null), the expression is completed.
If, for example, a variable should be changed to another value if its value evaluates to null, since C# 8.0 the
??=
null coalescing assignment operator can be used:
some_Value ??= some_Value2;
Which is a more concise version of:
some_Value = some_Value ?? some_Value2;
In combination with the
null-conditional operator ?.
or the null-conditional element access operator
?[]
the null coalescing operator can be used to provide a default value if an object or an object’s member is null. For example the following will return the default title if either the
page
object is null or
page
is not null but its
Title
property is:
string pageTitle = page?.Title ?? "Default Title";
CFML
As of
ColdFusion
Adobe ColdFusion is a commercial rapid web-application development computing platform created by J. J. Allaire in 1995. (The programming language used with that platform is also commonly called ColdFusion, though is more accurately known as ...
11,
Railo
Railo Server, commonly referred to as Railo ( ), is open source software which implements the general-purpose CFML server-side scripting language, often used to create dynamic websites, web applications and intranet systems. CFML is a dynami ...
4.1,
CFML
ColdFusion Markup Language, more commonly known as CFML, is a scripting language for web development that runs on the JVM, the .NET framework, and Google App Engine. Multiple commercial and open source implementations of CFML engines are availa ...
supports the null coalescing operator as a variation of the ternary operator,
?:
. It is functionally and syntactically equivalent to its C# counterpart, above. Example:
possiblyNullValue ?: valueIfNull
F#
The null value is not normally used in
F# for values or variables. However null values can appear for example when F# code is called from C#.
F# does not have a built-in null coalescing operator but one can be defined as required as a custom operator:
let (, ?) lhs rhs = (if lhs = null then rhs else lhs)
This custom operator can then be applied as per C#'s built-in null coalescing operator:
let pageTitle = suppliedTitle , ? "Default Title"
Freemarker
Missing values in
Apache FreeMarker will normally cause exceptions. However, both missing and null values can be handled, with an optional default value:
$
or, to leave the output blank:
$
Haskell
Types in
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
can in general not be null. Representation of computations that may or may not return a meaningful result is represented by the generic Maybe type, defined in the standard library as
data Maybe a = Nothing , Just a
The null coalescing operator replaces null pointers with a default value. The Haskell equivalent is a way of extracting a value from a Maybe by supplying a default value. This is the function fromMaybe.
fromMaybe :: a -> Maybe a -> a
fromMaybe defaultValue x =
case x of
Nothing -> defaultValue
Just value -> value
Some example usage follows.
fromMaybe 0 (Just 3) -- returns 3
fromMaybe "" Nothing -- returns ""
JavaScript
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
's nearest operator is
??
, the "nullish coalescing operator," which was added to the standard in
ECMAScript
ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262
ECMAScript is commonly used for client-side scriptin ...
's 11th edition. In earlier versions, it could be used via a
Babel
Babel is a name used in the Hebrew Bible for the city of Babylon and may refer to:
Arts and media Written works Books
*Babel (book), ''Babel'' (book), by Patti Smith
* Babel (2012 manga), ''Babel'' (2012 manga), by Narumi Shigematsu
* Babel (20 ...
plugin, and in
TypeScript
TypeScript is a free and open source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large appl ...
. It evaluates its left-hand operand and, if the result value is not "nullish" (
null
or
undefined
), takes that value as its result; otherwise, it evaluates the right-hand operand and takes the resulting value as its result.
In the following example,
a
will be assigned the value of
b
if the value of
b
is not
null
or
undefined
, otherwise it will be assigned 3.
const a = b ?? 3;
Before the nullish coalescing operator, programmers would use the logical OR operator (
, ,
). But where
??
looks specifically for
null
or
undefined
, the
, ,
operator looks for any
falsy value:
null
,
undefined
,
""
,
0
,
NaN
, and of course,
false
.
In the following example,
a
will be assigned the value of
b
if the value of
b
is
truthy, otherwise it will be assigned 3.
const a = b , , 3;
Kotlin
Kotlin uses the
?:
operator.
[.] This is an unusual choice of symbol, given that
?:
is typically used for the
Elvis operator
In certain computer programming languages, the Elvis operator, often written ?:, 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. This is ident ...
, not null coalescing, but it was inspired by
Groovy (programming language)
Apache Groovy is a Java-syntax-compatible object-oriented programming language for the Java platform. It is both a static and dynamic language with features similar to those of Python, Ruby, and Smalltalk. It can be used as both a programming la ...
where null is considered false.
val title = suppliedTitle ?: "Default title"
Objective-C
In
Obj-C, the nil coalescing operator is
?:
. It can be used to provide a default for nil references:
id value = valueThatMightBeNil ?: valueIfNil;
This is the same as writing
id value = valueThatMightBeNil ? valueThatMightBeNil : valueIfNil;
Perl
In
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
(starting with version 5.10), the operator is
//
and the equivalent Perl code is:
$possibly_null_value // $value_if_null
The ''possibly_null_value'' is evaluated as ''null'' or ''not-null'' (in Perl terminology, ''undefined'' or ''defined''). On the basis of the evaluation, the expression returns either ''value_if_null'' when ''possibly_null_value'' is null, or ''possibly_null_value'' otherwise. In the absence of
side-effects
In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
this is similar to the way
ternary operators
In mathematics, a ternary operation is an ''n''-ary operation with ''n'' = 3. A ternary operation on a set ''A'' takes any given three elements of ''A'' and combines them to form a single element of ''A''.
In computer science, a ternary operator ...
(
?:
statements) work in languages that support them. The above Perl code is equivalent to the use of the ternary operator below:
defined($possibly_null_value) ? $possibly_null_value : $value_if_null
This operator's most common usage is to minimize the amount of code used for a simple null check.
Perl additionally has a
//=
assignment operator, where
$a //= $b is largely equivalent to:
$a = $a // $b
This operator differs from Perl's older
, ,
and
, , =
operators in that it considers ''definedness,'' not ''truth.'' Thus they behave differently on values that are false but defined, such as 0 or '' (a zero-length string):
$a = 0;
$b = 1;
$c = $a // $b; # $c = 0
$c = $a , , $b; # $c = 1
PHP
PHP 7.0 introduced a null-coalescing operator with the
??
syntax. This checks strictly for NULL or a non-existent variable/array index/property. In this respect, it acts similarly to PHP's
isset()
pseudo-function:
$name = $request->input name'?? $request->query name'?? 'default name';
/* Equivalent to */
if (isset($request->input name') elseif (isset($request->query name') else
$user = $this->getUser() ?? $this->createGuestUser();
/* Equivalent to */
$user = $this->getUser();
if (null $user)
$pageTitle = $title ?? 'Default Title';
/* Equivalent to */
$pageTitle = isset($title) ? $title : 'Default Title';
Version 7.4 of PHP will add the Null Coalescing Assignment Operator with the
??=
syntax:
// The following lines are doing the same
$this->request->data comments''user_id'] = $this->request->data comments''user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data comments''user_id'] ??= 'value';
Python
Python does ''not'' have a null coalescing operator. Its functionality can be mimicked using a conditional expression:
now() if time is None else time
There was a proposal to add null-coalescing-type operators in Python 3.8, but that proposal has been deferred.
Related functionality
Python's operator provides a related, but different behavior. The difference is that also returns the right hand term if the first term is defined, but has a value that evaluates to in a boolean context:
42 or "something" # returns 42
0 or "something" # returns "something"
False or "something" # returns "something"
"" or "something" # returns "something"
[] or "something" # returns "something"
dict() or "something" # returns "something"
None or "something" # returns "something"
A true null coalescing operator would only return in the very last case, and would return the false-ish values (, , , , ) in the other examples.
PowerShell
Since PowerShell 7, the
??
null coalescing operator provides this functionality.
$myVar = $null
$x = $myVar ?? "something" # assigns "something"
Rust
While there's no
null
in
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH), ...
,
tagged union
In computer science, a tagged union, also called a variant, variant record, choice type, discriminated union, disjoint union, sum type or coproduct, is a data structure used to hold a value that could take on several different, but fixed, types. O ...
s are used for the same purpose. For example,
Result
or
Option
.
unwrap_or_else()
serves a similar purpose as the null coalescing operator in other languages. If the computation of the default value does not have side effects,
unwrap_or()
can be used as a more concise (and without optimizations, more efficient) choice.
let parsed_numbers: Vec<_> = 1", "not a number", "3" .iter()
.map(, n, n.parse().unwrap_or_else(, _, std::i64::MIN))
.collect();
// prints ", -9223372036854775808, 3
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline ...
println!("", parsed_numbers);
SQL
In Oracle's
PL/SQL
PL/SQL (Procedural Language for SQL) is Oracle Corporation's procedural extension for SQL and the Oracle relational database. PL/SQL is available in Oracle Database (since version 6 - stored PL/SQL procedures/functions/packages/triggers since ...
, the
NVL() function provides the same outcome:
NVL(possibly_null_value, 'value if null');
In
SQL Server/
Transact-SQL
Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to the SQL (Structured Query Language) used to interact with relational databases. T-SQL expands on the SQL standard to include procedural programming, local variables, vario ...
there is the ISNULL function that follows the same prototype pattern:
ISNULL(possibly_null_value, 'value if null');
Attention should be taken to not confuse ''ISNULL'' with ''IS NULL'' – the latter serves to evaluate whether some contents are defined to be ''NULL'' or not.
The ANSI SQL-92 standard includes the COALESCE function implemented in
Oracle
An oracle is a person or agency considered to provide wise and insightful counsel or prophetic predictions, most notably including precognition of the future, inspired by deities. As such, it is a form of divination.
Description
The wor ...
,
SQL Server,
PostgreSQL
PostgreSQL (, ), also known as Postgres, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. It was originally named POSTGRES, referring to its origins as a successor to the In ...
,
SQLite
SQLite (, ) is a database engine written in the C programming language. It is not a standalone app; rather, it is a library that software developers embed in their apps. As such, it belongs to the family of embedded databases. It is the mo ...
and
MySQL
MySQL () is an open-source relational database management system (RDBMS). Its name is a combination of "My", the name of co-founder Michael Widenius's daughter My, and "SQL", the acronym for Structured Query Language. A relational database ...
. The COALESCE function returns the first argument that is not null. If all terms are null, returns null.
COALESCE(possibly_null_value possibly_null_value, ...;
Swift
In
Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIFT ...
, the nil coalescing operator is
??
. It is used to provide a default when unwrapping an
optional type
In programming languages (especially functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions whic ...
:
optionalValue ?? valueIfNil
For example, if one wishes to implement some Swift code to give a page a default title if none is present, one may use the following statement:
var suppliedTitle: String? = ...
var pageTitle: String = suppliedTitle ?? "Default Title"
instead of the more verbose
var pageTitle: String = (suppliedTitle != nil) ? suppliedTitle! : "Default Title";
VB.NET
In
VB.NET the
If
[{{cite web, url=https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator, title=If Operator (Visual Basic), last=dotnet-bot, website=docs.microsoft.com] operator/keyword achieves the null coalescing operator effect.
Dim pageTitle = If(suppliedTitle, "Default Title")
which is a more concise way of using its variation
Dim pageTitle = If(suppliedTitle <> Nothing, suppliedTitle, "Default Title")
See also
*
?: (
conditional
Conditional (if then) may refer to:
* Causal conditional, if X then Y, where X is a cause of Y
* Conditional probability, the probability of an event A given that another event B has occurred
*Conditional proof, in logic: a proof that asserts a ...
)
*
Elvis operator
In certain computer programming languages, the Elvis operator, often written ?:, 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. This is ident ...
(binary ?:)
*
Null-conditional operator
*
Operator (programming)
In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.
Common simple examples include arithmetic (e.g. addition with ), co ...
References
Conditional constructs
Operators (programming)
Binary operations