Thursday 24 September 2020

Web Technologies and Syntax

JavaScript has a (newish) feature called optional chaining. Say I have code like:

const name = Data.person.name;

If person happens to not exist on Data, I’m going to get a hard, show-stopping error. With optional chaining, I can write:

const name = Data.person?.name;

Now if person doesn’t exist, name becomes undefined instead of throwing an error. That’s quite useful if you ask me. In a way, it makes for more resilient code, since there is less possibility of a script that entirely bombs out. But there are arguments that it actually makes for less resilient code, because instead of fixing the problem at the root level (bad data), you’re putting a band-aid on the problem.

Jim Nielsen makes the connection to optional chaining and !important in CSS. Errors of “undefined properties” are perhaps the most common of all JavaScript errors and optional chaining is a quick workaround. Styles that don’t cascade the way you want is (maybe?) the most common of all CSS issues and !important is a quick workaround.

Anyone familiar with CSS knows that using !important doesn’t always fix your problems. In fact, it might just cause you more problems. Ditto for optional chaining in JavaScript, it might cause you more problems than it fixes (we just don’t know it yet since it hasn’t been around long enough).

I like that take.

Sweeping negative hot takes about new features are just clickbait silliness, but sometimes there are good things buried in there to think about. I’ll bet optional chaining settles into some nice patterns in JavaScript, just like !important has in CSS to some degree. Most chatter I hear about !important in CSS lately is about how you should use it when you really mean it (not for getting out of a jam).

Direct Link to ArticlePermalink


The post Web Technologies and Syntax appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.



from CSS-Tricks https://ift.tt/31EVnRN
via IFTTT

No comments:

Post a Comment

Passkeys: What the Heck and Why?

These things called  passkeys  sure are making the rounds these days. They were a main attraction at  W3C TPAC 2022 , gained support in  Saf...