GO-Ve01
ServicesDevelopersBooksDictionaryPapersWikidataEncyclopediaSearchBabelCareersDeck

Null coalescing operator

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# since version 2.0, Dart since version 1.12.0, PHP since version 7.0.0, Perl 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, and otherwise returns the right-most operand. This behavior allows a default value to be... Source: e01 Encyclopedia. Licence: CC BY-SA 4.0.

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# since version 2.0, Dart since version 1.12.0, PHP since version 7.0.0, Perl 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, 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. supplied_title='supplied title' # Uncomment this line to use the supplied title title=${supplied_title:-'Default title'} echo "$title" # prints: Default title 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) { 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: 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"; possiblyNullValue ?: valueIfNull ${missingVariable!"defaultValue"} or, to leave the output blank: ${missingVariable!} 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; val title = suppliedTitle ?: "Default title" id value = valueThatMightBeNil ?: valueIfNil; This is the same as writing id value = valueThatMightBeNil ? valueThatMightBeNil : valueIfNil; $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 $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: // 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'; $myVar = $null $x = $myVar ?? "something" # assigns "something" > NULL %||% 2 [1] 2 // 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 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. 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. 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";

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"Null coalescing operator". 1791082553. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1378374483

JSON record · API collection · BibTeX · RIS · CSL-JSON · citation policy

Save to pass ·