7

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
1
  • 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, 2021 at 16:00

4 Answers 4

15

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

5

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

1

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

-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) ? [] : {})
2
  • 4
    ?? is not equivalent with ||. For instance 0 ?? 1 would return 0, however 0 || 1 would return 1.
    – Olian04
    Jun 13, 2021 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, 2021 at 15:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.