12

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
Olian04
  • 6,480
  • 2
  • 27
  • 54
Hamada
  • 1,836
  • 3
  • 13
  • 27
  • 1
    This means that the Node version you are running on does not yet support that operator. So *"it is possible?"*: not with that version of Node. – trincot Jun 13 '21 at 16:00

4 Answers4

19

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

trincot
  • 317,000
  • 35
  • 244
  • 286
7

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 :]

xddq
  • 341
  • 3
  • 7
1

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

Polygon
  • 50
  • 6
-1

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) ? [] : {})
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 4
    `??` is not equivalent with `||`. For instance `0 ?? 1` would return 0, however `0 || 1` would return 1. – Olian04 Jun 13 '21 at 15:44
  • @Olian04, that comment is not relevant here, since the object `o` is completely controlled by this `reduce` call, and its properties are always objects. – trincot Jun 13 '21 at 15:58