How does the Null-Coalescing Operator (??) work in Spider?

2.4k views Asked by At

Spider's null-coalescing operator ?? returns the right expression if the left expression is null or undefined.

var name = options.name ?? "default name";

How does it work?

1

There are 1 answers

0
Alon Gubkin On BEST ANSWER

The null-coalescing operator usually works with a simple conditional expression. For example, this code in Spider:

var name = options.name ?? "default name";

compiles to the following JavaScript:

var name = options.name == null ? "default name" : options.name;

(more about equals equals null)

Undefined Identifier Problem

Note that if the left expression is an identifier, and that identifier is undefined, then the JS interpreter would raise an error. To solve this, the Spider compiler adds an undefined check. For example this code in Spider:

var name = name ?? "value";

compiles to the following code in JS:

var name = typeof name === "undefined" || name == null ? "value" : name;

Note that if you want to do something like options.name ?? "default" and you're not sure if options is defined or not, you can use the null propagating operator:

var name = options?.name ?? "default";

Double Function Call Problem

If the left expression is a call expression (e.g fn()), then it might get called twice - the first time for the null test, and the second time for the value. To solve this, the Spider compiler moves the call expression to a different variable. For example this code in Spider:

var name = getName() ?? "default name";

is compiled into something like:

var tmp = getName();
var name = tmp == null ? "default name" : tmp;

Statement Problem

If the null-coalescing operator is used as a statement and not as an expression, for example:

a() ?? b();

then the Spider compiler uses an if statement instead of a conditional expression:

if (a() == null) {
  b();
}