Safe Default (??) Operator

Summary

Evalutes the left-hand side. If the result is not null or undefined, it is returned. Otherwise, the evaluated value of the right-hand side is returned.

Syntax

expression1 ?? expression2

Parameters

expression1
Any legal expression.
expression2
Any legal expression.

Description

Evalutes the left-hand side. If the result is not null or undefined, it is returned. Otherwise, the evaluated value of the right-hand side is returned.

If the evaluated value of both sides of the expression is null, the value null is returned. If the evaluated value of both sides of the expression is undefined, the value undefined is returned.

This operator may also be known as the "null coalescing" operator. However, in JS++, this operator also handles undefined.

Handling Out-of-Bounds Accesses

The safe default operator is commonly used with existent types to safely deal with out-of-bounds accesses. Basic usage might look like this:

1
2
3
4
5
6
7
import System;
 
int[] arr = [ 1, 2, 3 ];
int+ x = arr[100]; // out-of-bounds access occurred
int y = x ?? 5;
 
Console.log(y); // 5

Examples

Using the safe default operator to provide an alternative value after an out-of-bounds access
1
2
3
4
5
6
7
import System;
 
int[] arr = [ 1, 2, 3 ];
int+ x = arr[100];
int y = x ?? 5;
 
Console.log(y); // 5

See Also

Share

HTML | BBCode | Direct Link