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

+3


source to share


1 answer


The zero connectivity operator usually works with a simple conditional expression. For example, this code in Spider:

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

      

the following JavaScript is compiled:

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

      

(more about equals is zero)

Undefined Problem with ID

Note that if the left expression is an identifier and this identifier is undefined, then the JS interpreter throws an error. To solve this problem, 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

defined or not, you can use the null spread operator:



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

      

Double function call problem

If the left expression is a call expression (for example, fn()

), then it can be called twice - the first time for the null test and the second time for the value. To solve this problem, the Spider compiler moves the call expression to a different variable. For example, this code in Spider:

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

      

compiled into something like:

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

      

Problem with message

If the null-coalescing operator is used as an operator 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();
}

      

+5


source







All Articles