0

When I do this:

  var resetButton = document.querySelector('.resetButton');
  resetButton?.onclick = function() {
   //...
  };

I got error: Uncaught SyntaxError: invalid assignment left-hand side.
I would like to be able to use optional chaining on every object.

Zorro
  • 1,085
  • 12
  • 19
  • I believe you are looking for the nullish coalescing assignment operator: [`??=`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment). Wrap the outer objects in something like `((foo ??= {}).bar ??= {}).baz ??= qux`. – InSync Jun 17 '23 at 01:50
  • Counter-example: if the left-hand-side `?.` expression evaluates to `null`, then should the right-hand-side expression still be evaluated... or not? I suspect that's the reason why it isn't supported (because if the right-hand-side has side-effects but the left-hand-side is `null` then that's _probably_ a bug, so probably better to avoid that situation entirely). – Dai Jun 17 '23 at 01:51
  • 2
    @AlexT. JS added the `?.` operator sometime around 2019-2020: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining – Dai Jun 17 '23 at 01:52
  • Not actually "*recently*" *per se*, as browsers started supporting it three years ago. – InSync Jun 17 '23 at 01:53
  • @InSync It's still "recent" to me: the last 3 years have kinda been a blur for me... also, a major blocker for newer JS features is now Safari, as users with older iPhones will be stuck on older iOS + Safari versions - and you can't polyfill support for syntax features :/ – Dai Jun 17 '23 at 01:56
  • Ok guys look just not supported like said on doc page privided by @AlexT. Thanks – Zorro Jun 17 '23 at 01:59
  • Babel/TS [can](https://www.typescriptlang.org/play?target=0#code/MYewdgzgLgBAZiEMC8MwFcA2mDcAoPUSETAUwDpMQBzACgRAH5yAjAQwCdn2AvASnx5a9RDEaNUAbwC+fVpzESYMubxQwA5AEd0ADw1A) :) – InSync Jun 17 '23 at 02:00

1 Answers1

0

'?.' is used when you want to access something that may be undefined(no errors)?. does not return any reference so you can't use it to assign.