Hamada
Hamada

Reputation: 1898

Nullish coalescing assignment operator (??=) in NodeJS

I'm trying to use the Nullish coalescing assignment operator (??=) in NodeJS, it is possible?

const setValue = (object, path, value) => {
  const indices = {
      first: 0,
      second: 1
    },
    keys = path.replace(new RegExp(Object.keys(indices).join('|'), 'g'), k => indices[k]).split('.'),
    last = keys.pop();

  keys
    .reduce((o, k, i, kk) => o[k] ??= isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}, object)[last] = value;

  return obj;
}
est.js:9
       .reduce((o, k, i, kk) => o[k] ??= isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}, object)
                                      ^

SyntaxError: Unexpected token '?'
        at wrapSafe (internal/modules/cjs/loader.js:1067:16)
        at Module._compile (internal/modules/cjs/loader.js:1115:27)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
        at Module.load (internal/modules/cjs/loader.js:1000:32)
        at Function.Module._load (internal/modules/cjs/loader.js:899:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
        at internal/main/run_main_module.js:17:47

Upvotes: 13

Views: 17778

Answers (4)

xddq
xddq

Reputation: 381

It's possible for node version v15.14+.

The rewrite for something like

a.greeting ??= "hello"

in node <v15.14 is:

a.greeting = a?.greeting ?? 'hello'

Maybe it does help someone :]

Upvotes: 8

Nina Scholz
Nina Scholz

Reputation: 386766

You could replace logical nullish assignment ??=

o[k] ??= isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {}

with an assignment with logical OR ||

o[k] = o[k] || (isFinite(i + 1 in kk ? kk[i + 1] : last) ? [] : {})

Upvotes: -1

trincot
trincot

Reputation: 351029

The error means your version of Node does not yet have support for the ??= operator.

Check out the versions which support it on node.green:

enter image description here

Upvotes: 21

Polygon
Polygon

Reputation: 38

The node version you are using doesn't support the nullish coalescing assignment operator.

Upvotes: 0

Related Questions