Null coalescing operator
   HOME

TheInfoList



OR:

The null coalescing operator is a binary operator 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. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s, such as (in alphabetical order): C# since version 2.0, Dart since version 1.12.0, PHP since version 7.0.0,
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
since version 5.10 as ''logical defined-or'', PowerShell since 7.0.0, and Swift as ''nil-coalescing operator''. It is most commonly written as x ?? y, but varies across programming languages. 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 Astronomy *Nuller, an optical tool using interferometry to block certain sources of light Computing *Null (SQL) (or NULL), a special marker and keyword in SQL indicating that a data value do ...
, 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. Like the binary Elvis operator, usually written as x ?: y, the null coalescing operator is a short-circuiting operator and thus does not evaluate the second operand if its value is not used, which is significant if its evaluation has side-effects.


Examples by languages


Bourne-like shells

In Bourne shell (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. 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 11, Railo 4.1, CFML 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


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: $


JavaScript

JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
's nearest operator is ??, the "nullish coalescing operator", which was added to the standard in
ECMAScript ECMAScript (; ES) is a standard for scripting languages, including JavaScript, JScript, and ActionScript. It is best known as a JavaScript standard intended to ensure the interoperability of web pages across different web browsers. It is stan ...
's 11th edition. In earlier versions, it could be used via a Babel plugin, and in
TypeScript TypeScript (abbreviated as TS) is a high-level programming language that adds static typing with optional type annotations to JavaScript. It is designed for developing large applications and transpiles to JavaScript. It is developed by Micr ...
. 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, not null coalescing, but it was inspired by Groovy (programming language) 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 high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
(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 this is similar to the way ternary operators ( ?: 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 ($user

null)
$pageTitle = $title ?? 'Default Title'; /* Equivalent to */ $pageTitle = isset($title) ? $title : 'Default Title'; Version 7.4 of PHP introduced 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';


PowerShell

Since PowerShell 7, the ?? null coalescing operator provides this functionality. $myVar = $null $x = $myVar ?? "something" # assigns "something"


R

Since R (programming language), R version 4.4.0 the %, , % operator is included in base R (previously it was a feature of some packages like ''rlang''). > NULL %, , % 2 2


Rust

While there's no null in Rust, tagged unions are used for the same purpose. For example, Result or Option. Any type implementing the Try trait can be unwrapped. unwrap_or() serves a similar purpose as the null coalescing operator in other languages. Alternatively, unwrap_or_else() can be used to use the result of a function as a default value. // Option // An Option can be either Some(value) or None Some(1).unwrap_or(0); // evaluates to 1 None.unwrap_or(0); // evaluates to 0 None.unwrap_or_else(get_default); // evaluates to the result of calling the function get_default // Result // A Result can be either Ok(value) or Err(error) Ok(1).unwrap_or(0); // evaluates to 1 Err("oh no").unwrap_or(1); // evaluates to 1


SQL

In Oracle's PL/SQL, the NVL() function provides the same outcome: NVL(possibly_null_value, 'value if null'); In SQL Server/ Transact-SQL 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, SQL Server, PostgreSQL, SQLite and
MySQL MySQL () is an Open-source software, 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 rel ...
.{{cite web, url=http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce, title=MySQL :: MySQL 5.5 Reference Manual :: 12.3.2 Comparison Functions and Operators, website=dev.mysql.com 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, ...; The difference between ISNULL and COALESCE is that the type returned by ISNULL is the type of the leftmost value while COALESCE returns the type of the first non-null value.


Swift

In Swift, the nil coalescing operator is ??. It is used to provide a default when unwrapping an optional type: 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";


See also

* ?: ( conditional) * Elvis operator (binary ?:) * Null-conditional operator *
Operator (computer programming) In computer programming, an operator is a programming language construct that provides functionality that may not be possible to define as a user-defined function (i.e. sizeof in C) or has syntax different than a function (i.e. infix addit ...


References

Conditional constructs Operators (programming) Binary operations