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).
I’m not so sure that it’s that big of a deal. In the example, when we later need to use the
name
constant, we’ll need to make sure that we have a valid value. Even ifData.person
is goodData.person.name
may not be what we expect.So, in the future when we need to use
name
, and we no longer care aboutData.person
, we just check thatname
is set and is what we expect.Optional chaining in this instance allows us to quickly deal with the non existent person and let us get on with our day. That said, I don’t use it.
Had waited for this to make ternary checks less obtuse. I have cases where I fill objects on the go, and I don’t always know if properties are there yet.
Instead of, say:
let a = b && b.c && b.c.d || 1;
I can write:
let a = b?.c?.d || 1;
I don’t see this as going to change anything for myself or the teams I work with at least.
I think it’s generally understood best practice to do error checking at the start of a function when necessary, and reacting accordingly. This doesn’t change that logic or the things we need to look for, it just makes it less to write, and arguably easier to read.
That said, I don’t use this feature yet due to browser support.