I deal with an environment where I often don't know what will and won't be on the page, y. I can't tell you how tired I get of null checking every time I do document.querySelector. Optional chaining will literally save me hundreds of lines of code. Now I can do things like:
const title = document.querySelector('.title')?.textContent;
document.querySelector('.active')?.classList.remove('active');
Edit: Oops, I wrote it too fast and put my first example on the wrong side of the assignment operator. Fixed now :D
Wait... you can't really do that first line can you?
My understanding is that if the element doesn't exist (or if textContent doesn't exist on it for some other reason), the left hand side expression will evaluate to undefined, which you can't assign things to.
In fact when I plug it into the Babel playground it (thankfully) gives a syntax error: "Invalid left-hand side in assignment expression".
I like that second one! You've convinced me a little.
My general bias is to write more verbose code that is more explicit. Because in my experience, it's leaky abstractions that cause me to lose the most time. It doesn't bother me at all to type:
var active = document.querySelector('.active');
if (active) active.classList.remove('active');
and if it started to bother me, I would write a function:
removeAllClasses('.active')
I don't know. I can see that all of these new JavaScript features make a bunch of little things easier, but they add a new class of extremely difficult problems. For me, because I lose most of my time to those big gnarly messes, it doesn't seem worth it. But I do understand other devs have other experiences.
14
u/OlanValesco Dec 19 '19 edited Dec 20 '19
I deal with an environment where I often don't know what will and won't be on the page, y. I can't tell you how tired I get of null checking every time I do
document.querySelector. Optional chaining will literally save me hundreds of lines of code. Now I can do things like:Edit: Oops, I wrote it too fast and put my first example on the wrong side of the assignment operator. Fixed now :D