1

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.

7
  • I believe you are looking for the nullish coalescing assignment operator: ??=. Wrap the outer objects in something like ((foo ??= {}).bar ??= {}).baz ??= qux. Commented Jun 17, 2023 at 1: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). Commented Jun 17, 2023 at 1:51
  • 3
    @AlexT. JS added the ?. operator sometime around 2019-2020: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 17, 2023 at 1:52
  • Not actually "recently" per se, as browsers started supporting it three years ago. Commented Jun 17, 2023 at 1: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 :/ Commented Jun 17, 2023 at 1:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.