Nullish coalescing operator in ActionScript

The ?? operator

Apache Royale adds support for the nullish coalescing operator in ActionScript, which uses the symbol ??. The ?? operator accepts two operands, one each on its left and right sides. Which operand is returned depends on whether the left operand is nullish or not.

Nullish values include null and undefined only. If the left operand is not nullish, then it is returned immediately, without executing the right operand. If the left operand is nullish, then the right operand is returned instead.

Requires Apache Royale 0.9.10 or newer.

Code example

Consider the following code that uses the ?? operator to provide a non-null value if the left operand is nullish.

var obj:Object = null;
trace(obj == null); // true
var resolved:Object = obj ?? {};
trace(obj == null); // false

The next code shows that the left operand will be returned when it is not nullish.

var obj:Object = {};
var resolved:Object = obj ?? {};
trace(resolved == obj); // true

The code below demonstrates the difference between ?? and || when encountering a falsy value.

var num:Number = 0;
var checkNullish:Number = num ?? -1;
var checkFalsy:Number = num || -1;
trace(checkNullish == -1); // false
trace(checkFalsy == -1); // true

Limitations of the nullish coalescing operator in Royale

Other ActionScript compilers, such as the one in the Apache Flex SDK, may not recognize the nullish coalescing operator. Attemping to pass ActionScript or MXML source code that contains nullish coalescing operators to another compiler may result in compile-time errors. In other words, to write 100% portable ActionScript code that works with any compiler, avoid using nullish coalescing operator and any of Royale’s other extensions to the ActionScript language.