Null coalescing operator

Last updated

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.

Contents

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.

Examples by languages

ATS

As with most languages in the ML family, ATS uses algebraic data types to represent the absence of a value instead of null. A linearly-typed optional dataviewtype could be defined as

dataviewtype option_vt (a: t@ype, bool) =  | None_vt(a, false)  | Some_vt(a, true) of a viewtypedef Option_vt(a: t@ype) = [b:bool] option_vt(a, b)

A function with a provided default value can then pattern match on the optional value to coalesce:

fn {a:t@ype} value (default: a, opt: Option_vt a): a =  case+ opt of  | ~None_vt() => default  | ~Some_vt(x) => x

Which can for example be used like:

value<int>(42, None_vt)    // returns 42 value<int>(42, Some_vt(7)) // returns 7

If one wanted to then define an infix operator:

fn {a:t@ype} flipped_value (opt: Option_vt a, default: a): a =  value(default, opt)  infixr 0 ?? #define ?? flipped_value

Which can for example be used like:

None_vt{int} ?? 42    // returns 42 Some_vt{int}(7) ?? 42 // returns 7

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": [9]

#supplied_title='supplied title' # Uncomment this line to use the supplied titletitle=${supplied_title:-'Default 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:

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

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

stringpageTitle=page?.Title??"Default Title";

CFML

As of ColdFusion 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 

F#

The null value is not normally used in F# for values or variables. [12] 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: [13]

let(|?)lhsrhs=(iflhs=nullthenrhselselhs)

This custom operator can then be applied as per C#'s built-in null coalescing operator:

letpageTitle=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: [14]

${missingVariable!"defaultValue"}

or, to leave the output blank:

${missingVariable!}

Haskell

Types in Haskell 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 [15] as

dataMaybea=Nothing|Justa

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->Maybea->afromMaybedefaultValuex=casexofNothing->defaultValueJustvalue->value

Some example usage follows.

fromMaybe0(Just3)-- returns 3fromMaybe""Nothing-- returns ""

JavaScript

JavaScript's nearest operator is ??, the "nullish coalescing operator", which was added to the standard in ECMAScript's 11th edition. [16] In earlier versions, it could be used via a Babel plugin, and in TypeScript. 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.

consta=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.

consta=b||3;

Kotlin

Kotlin uses the ?: operator. [17] 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.

valtitle=suppliedTitle?:"Default title"

Objective-C

In Obj-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;

Perl

In Perl (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 [18] 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'])){$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 will add the Null Coalescing Assignment Operator with the ??= syntax: [19]

// 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()iftimeisNoneelsetime

There was a proposal to add null-coalescing-type operators in Python 3.8, but that proposal has been deferred. [20]

Python's or operator provides a related, but different behavior. The difference is that or also returns the right hand term if the first term is defined, but has a value that evaluates to False in a boolean context:

42or"something"# returns 420or"something"# returns "something"Falseor"something"# returns "something"""or"something"# returns "something"[]or"something"# returns "something"dict()or"something"# returns "something"Noneor"something"# returns "something"

A true null coalescing operator would only return "something" in the very last case, and would return the false-ish values (0, False, "", [], dict()) in the other examples.

PowerShell

Since PowerShell 7, the ?? null coalescing operator provides this functionality. [7]

$myVar=$null$x=$myVar??"something"# assigns "something"

R

Since R version 4.4.0 %||% operator is included in base R (previously it was a feature of some packages like rlang).

Ruby

Ruby does not have a null-coalescing operator, but its || and ||= operators work the same way except on Booleans. Ruby conditionals have only two false-like values: false and nil (where 'false' is not the same as 0). Ruby's || operator evaluates to its first operand when true-like. In comparison, Perl/Python/Javascript, which also have the latter property, have other false-like values (0 and empty string), which make || differ from a null-coalescing operator in many more cases (numbers and strings being two of the most frequently used data types). This is what led Perl/Python/Javascript to add a separate operator while Ruby hasn't.

Rust

While there's no null in Rust, tagged unions are used for the same purpose. For example, Result<T, E> or Option<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

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, [21] SQL Server, [22] PostgreSQL, [23] SQLite [24] and MySQL. [25] 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:

varsuppliedTitle:String?=...varpageTitle:String=suppliedTitle??"Default Title"

instead of the more verbose

varpageTitle:String=(suppliedTitle!=nil)?suppliedTitle!:"Default Title";

VB.NET

In VB.NET the If [26] operator/keyword achieves the null coalescing operator effect.

DimpageTitle=If(suppliedTitle,"Default Title")

which is a more concise way of using its variation

DimpageTitle=If(suppliedTitle<>Nothing,suppliedTitle,"Default Title")

See also

Related Research Articles

Null may refer to:

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language constructs that perform different computations or actions or return different values depending on the value of a Boolean expression, called a condition.

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, conditional expression, ternary if, or inline if. An expression if a then b else c or a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is the most common, but alternative syntax do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.

In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.

<span class="mw-page-title-main">Boolean data type</span> Data having only values "true" or "false"

In computer science, the Boolean is a data type that has one of two possible values which is intended to represent the two truth values of logic and Boolean algebra. It is named after George Boole, who first defined an algebraic system of logic in the mid 19th century. The Boolean data type is primarily associated with conditional statements, which allow different actions by changing control flow depending on whether a programmer-specified Boolean condition evaluates to true or false. It is a special case of a more general logical data type—logic does not always need to be Boolean.

In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality and inequalities.

<span class="mw-page-title-main">Null (SQL)</span> Marker used in SQL databases to indicate a value does not exist

In SQL, null or NULL is a special marker used to indicate that a data value does not exist in the database. Introduced by the creator of the relational database model, E. F. Codd, SQL null serves to fulfil the requirement that all true relational database management systems (RDBMS) support a representation of "missing information and inapplicable information". Codd also introduced the use of the lowercase Greek omega (ω) symbol to represent null in database theory. In SQL, NULL is a reserved word used to identify this marker.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

In computing, IIf is a function in several editions of the Visual Basic programming language and ColdFusion Markup Language (CFML), and on spreadsheets that returns the second or third parameter based on the evaluation of the first parameter. It is an example of a conditional expression, which is similar to a conditional statement.

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type. In statically typed languages, a nullable type is an option type, while in dynamically typed languages, equivalent behavior is provided by having a single null value.

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior, was first published as "Void Value" and later in the Pattern Languages of Program Design book series as "Null Object".

Language Integrated Query is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, originally released as a major part of .NET Framework 3.5 in 2007.

The computer programming language, C#, introduces several new features in version 2.0. These include:

In computing, undefined value is a condition where an expression does not have a correct value, although it is syntactically correct. An undefined value must not be confused with empty string, Boolean "false" or other "empty" values. Depending on circumstances, evaluation to an undefined value may lead to exception or undefined behaviour, but in some programming languages undefined values can occur during a normal, predictable course of program execution.

The Is functions are a set of functions in Microsoft's Visual Basic 6, Visual Basic for Applications, VBScript, and Visual Basic .NET. Several of them are also provided in Transact-SQL by the .NET Framework Data Provider for Microsoft SQL Server.

In certain computer programming languages, the Elvis operator, often written ?:, is a binary operator that returns the evaluated first operand if that operand evaluates to a value likened to logically true, and otherwise returns the evaluated second operand. This is identical to a short-circuit or with "last value" semantics. The notation of the Elvis operator was inspired by the ternary conditional operator, ? :, since the Elvis operator expression A ?: B is approximately equivalent to the ternary conditional expression A ? A : B.

In object-oriented programming, the safe navigation operator is a binary operator that returns null if its first argument is null; otherwise it performs a dereferencing operation as specified by the second argument.

In database theory, Imieliński–Lipski algebra is an extension of relational algebra onto tables with different types of null values. It is used to operate on relations with incomplete information.

The syntax of the SQL programming language is defined and maintained by ISO/IEC SC 32 as part of ISO/IEC 9075. This standard is not freely available. Despite the existence of the standard, SQL code is not completely portable among different database systems without adjustments.

References

  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. 1 2 "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.
  9. "Bash man page".
  10. "Elvis operator". wikidocs.adobe.com.
  11. "[RAILO-2195] add support for the Elvis Operator". JBoss Issue Tracker.
  12. cartermp. "Null Values (F#)". msdn.microsoft.com.
  13. cartermp. "Operator Overloading (F#)". msdn.microsoft.com.
  14. "Expressions". Apache FreeMarker Manual.
  15. "Hackage" . Retrieved 10 July 2015.
  16. "ECMAScript 2020 Language Specification". Ecma International. June 2020.
  17. "Null safety"..
  18. "PHP: rfc:isset_ternary" . Retrieved 16 December 2014.
  19. Kocak, Midori. "PHP RFC: Null Coalescing Assignment Operator". PHP.net. Retrieved 20 July 2017.
  20. "PEP 505 -- None-aware operators".
  21. "Database SQL Language Reference". docs.oracle.com.
  22. "COALESCE (SQL Server Compact)". technet.microsoft.com.
  23. "PostgreSQL: Documentation: 9.1: Conditional Expressions". www.postgresql.org. 27 October 2016.
  24. "SQLite Query Language: Core Functions". www.sqlite.org.
  25. "MySQL :: MySQL 5.5 Reference Manual :: 12.3.2 Comparison Functions and Operators". dev.mysql.com.
  26. dotnet-bot. "If Operator (Visual Basic)". docs.microsoft.com.