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?
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?
The null-coalescing operator usually works with a simple conditional expression. For example, this code in Spider:
compiles to the following JavaScript:
(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:
compiles to the following code in JS:
Note that if you want to do something like
options.name ?? "default"
and you're not sure ifoptions
is defined or not, you can use the null propagating operator: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:is compiled into something like:
Statement Problem
If the null-coalescing operator is used as a statement and not as an expression, for example:
then the Spider compiler uses an if statement instead of a conditional expression: