Thenull coalescing operator is abinary operator that is part of the syntax for a basicconditional expression in severalprogramming 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 aslogical defined-or,[6]PowerShell since 7.0.0,[7] andSwift[8] asnil-coalescing operator. It is most commonly written asx ?? 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 notnull, 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 binaryElvis operator, usually written asx ?: y, the null coalescing operator is ashort-circuiting operator and thus does not evaluate the second operand if its value is not used, which is significant if its evaluation hasside-effects.
InBourne shell (and derivatives), "Ifparameter is unset or null, the expansion ofword is substituted. Otherwise, the value ofparameter is substituted":[9]
#supplied_title='supplied title' # Uncomment this line to use the supplied titletitle=${supplied_title:-'Default title'}echo"$title"# prints: Default title
InC#, 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:
stringpageTitle=suppliedTitle??"Default Title";
instead of the more verbose
stringpageTitle=(suppliedTitle!=null)?suppliedTitle:"Default Title";
or
stringpageTitle;if(suppliedTitle!=null){pageTitle=suppliedTitle;}else{pageTitle="Default Title";}
The three forms result in the same value being stored into the variable namedpageTitle.
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:
returnsome_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 thenull-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 thepage object is null orpage is not null but itsTitle property is:
stringpageTitle=page?.Title??"Default Title";
As ofColdFusion 11,[10]Railo 4.1,[11]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
Missing values inApache FreeMarker will normally cause exceptions. However, both missing and null values can be handled, with an optional default value:[12]
${missingVariable!"defaultValue"}
or, to leave the output blank:
${missingVariable!}
JavaScript's nearest operator is??, the "nullish coalescing operator", which was added to the standard inECMAScript's 11th edition.[13] In earlier versions, it could be used via aBabel plugin, and inTypeScript. It evaluates its left-hand operand and, if the result value isnot "nullish" (null orundefined), 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 ofb if the value ofb is notnull orundefined, otherwise it will be assigned 3.
consta=b??3;
Before the nullish coalescing operator, programmers would use the logical OR operator (||). But where?? looks specifically fornull orundefined, the|| operator looks for anyfalsy value:null,undefined,"",0,NaN, and of course,false.
In the following example,a will be assigned the value ofb if the value ofb istruthy, otherwise it will be assigned 3.
consta=b||3;
Kotlin uses the?: operator.[14] This is an unusual choice of symbol, given that?: is typically used for theElvis operator, not null coalescing, but it was inspired byGroovy (programming language) where null is considered false.
valtitle=suppliedTitle?:"Default title"
InObj-C, the nil coalescing operator is?:. It can be used to provide a default for nil references:
idvalue=valueThatMightBeNil?:valueIfNil;
This is the same as writing
idvalue=valueThatMightBeNil?valueThatMightBeNil:valueIfNil;
InPerl (starting with version 5.10), the operator is// and the equivalent Perl code is:
$possibly_null_value//$value_if_null
Thepossibly_null_value is evaluated asnull ornot-null (in Perl terminology,undefined ordefined). On the basis of the evaluation, the expression returns eithervalue_if_null whenpossibly_null_value is null, orpossibly_null_value otherwise. In the absence ofside-effects this is similar to the wayternary 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 considersdefinedness, nottruth. 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 7.0 introduced[15] 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'sisset() pseudo-function:
$name=$request->input['name']??$request->query['name']??'default name';/* Equivalent to */if(isset($request->input['name'])){$name=$request->input['name'];}elseif(isset($request->query['name'])){$name=$request->query['name'];}else{$name='default name';}
$user=$this->getUser()??$this->createGuestUser();/* Equivalent to */$user=$this->getUser();if($user===null){$user=$this->createGuestUser();}
$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:[16]
// 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';
Since PowerShell 7, the?? null coalescing operator provides this functionality.[7]
$myVar=$null$x=$myVar??"something"# assigns "something"
SinceR version 4.4.0 the%||% operator is included in base R (previously it was a feature of some packages likerlang).[17]
>NULL%||%2[1]2
While there's nonull inRust,tagged unions are used for the same purpose. For example,Result<T, E> orOption<T>.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 NoneSome(1).unwrap_or(0);// evaluates to 1None.unwrap_or(0);// evaluates to 0None.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 1Err("oh no").unwrap_or(1);// evaluates to 1
In Oracle'sPL/SQL, theNVL() function provides the same outcome:
NVL(possibly_null_value,'value if null');
InSQL 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 confuseISNULL withIS NULL – the latter serves to evaluate whether some contents are defined to beNULL or not.
The ANSI SQL-92 standard includes the COALESCE function implemented inOracle,[18]SQL Server,[19]PostgreSQL,[20]SQLite[21] andMySQL.[22] 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.
InSwift, the nil coalescing operator is??. It is used to provide a default when unwrapping anoptional 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:
varsuppliedTitle:String?=...varpageTitle:String=suppliedTitle??"Default Title"
instead of the more verbose
varpageTitle:String=(suppliedTitle!=nil)?suppliedTitle!:"Default Title";