ES2020 (ES11)

Another set of useful functionalities used often in MapStore from ES2020.

Optional Chaining

Shortener for null or undefined (nullish) checks, returning undefined if something is nullish in the chain.

In the example below, // if obj.attr1 doesn’t have attr2, you have an error

const obj = {
    attr1: {}
}:
const a = obj.attr1.attr2.attr3;
// ERROR:
// Uncaught TypeError: Cannot read property 'attr3' of undefined

To prevent issues you usually needed to do something like this…

const a = obj.attr1 && attr1.attr2 && attr1.attr2.attr3;

This method anyway has a set of issues:

  • long
  • Implicit conversion can anyway have false positive (e.g. when you have numeric or boolean values).

with optional chaining you can shorten the operation above this way:

const a = obj?.attr1?.attr2?.attr3;

it can be used for:
obj?.prop // object properties
obj?.["expr"] // object props accessed with [] operator
arr?.[1] // arrays
func?.(args) // functions, prevents errors if function is undefined on function call.

Nullish Coalescing

Returns default values in case of nullish. Is more secure than the usual && || checks, because it works also in case of values 0 or empty strings (that are false)

const a = null;
const foo = a ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0