Is Optional Chaining Really a Good Addition to JavaScript?
Originally published on medium .
Optional Chaining in JavaScript is a syntax that allows you to access deeply nested objects safely without having to do multiple if (...) or && checks like the following:
// Without optional chaining
let street;
if (user && user.address && user.address.street) {
street = user.address.street;
}
// With optional chaining
const street = user?.address?.street;
So, it’s basically a more concise way of safely accessing deeply nested properties. Nothing can go wrong, right? Well, not exactly.
The problem with Optional Chaining
The keyphrase to take from the previous code snippet is that you should use it when you’re legitimately not sure if a property exists or not. That should be the only time where you ever use optional chaining. Consider the following code snippet:
// Over-defensive code encouraged by optional chaining
const user = await User.findById(userId);
const name = user?.name;
const email = user?.email;
const address = user?.address?.street;
In the user returned from the database, we expect that all the properties exist. If one of the properties does not exist, it means there is something wrong happened somewhere, and you better get notified about it by having an error thrown at your face as soon as you can.
Developers tend to prefer having things fail silently instead of errors being thrown ASAP, because who wants to see an error, right? But if something is wrong, an error will eventually be thrown somewhere, or even worse, nothing will be thrown at all but you’ll end up with undesired behavior without knowing what’s wrong. It’s up to you to decide how soon you want to know something is wrong, and where it went wrong.
The convenience that optional chaining presents will push developers into not taking their time to think whether or not they should actually safely access this property, and just using it to avoid errors by the cost of nasty bugs that are difficult to debug.
Conclusion
JavaScript Optional Chaining is definitely an addition to look forward to and has very good use cases, but if used carelessly, it will do more damage than good.