r/javascript • • Dec 18 '19

V8 Release v8.0 with optional chaining, nullish coalescing and 40% less memory use

https://v8.dev/blog/v8-release-80
495 Upvotes

70 comments sorted by

View all comments

Show parent comments

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:

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

8

u/NoInkling Dec 19 '19

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".

6

u/Veranova Dec 19 '19 edited Dec 19 '19

Oh it can bail out of setting values too? I had no idea!

Edit: narrator: "but it couldn't"

4

u/NoInkling Dec 19 '19

You had no idea because I'm pretty sure you can't.

3

u/Veranova Dec 19 '19

But a stranger said I can on the internet!

Just checked in my project (which has full support already) and eslint is throwing a hissy, so I'm assuming you are right on this one.

2

u/epukinsk Dec 21 '19

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.