r/javascript • • Feb 20 '18

Optional Chaining may be coming to JavaScript

https://dev.to/sammyisa/optional-chaining-may-be-coming-to-javascript--4ff0
321 Upvotes

100 comments sorted by

View all comments

1

u/Pesthuf Feb 20 '18

How much work is it to make a Stage 0 proposal for TC39?

I'd really like to get some discussion on Dart-inspred Cascade notation - A sort of operator (..) that works like "." expect that it returns the left hand side object - that would allow having jQuery-like, fluent APIs for basically every object (even existing, ancient APIs), without creating the overhead that a fluent API wrapper or even a whole library would, or forcing people to use return this in every method instead of returning something potentially useful.

Basically, it's supposed to allow things like

new XMLHttpRequest()..open('GET', '/test.json')..onload = () => console.log('Done!')..send();

or

document.querySelector('#div')
..textContent = 'Hi!'
..addEventListener('click', () => console.log('hi!'))
..classList.add('very-important');

Do you need to already write parser rules and everything for a stage 0 strawman? Are proposals welcome at all?

0

u/[deleted] Feb 21 '18

[deleted]

1

u/Pesthuf Feb 21 '18

True, but can't the same be done for this optional chaining feature as well?

Also the classlist part is a bit dirty, since it's no longer part of the cascade. You can't do

..classlist.add('lol')
..setAttribute('whatever', 'whatever')

after it.

I've always felt like using functions like this for this problem seems overkill. I probably wouldn't do it in my code. One less dependency.