risks of ?'s

The optional chaining operator is a great tool for code clarity. The messy nest of if-checking down a deep object well has always been a readability nightmare in every language.

That said, it is a syntactic sugar that can fill your code with unneeded checks, and it is also not without some risks if not used well.

Optional Chaining is syntactic sugar, and like any sugar, it isn't free. It looks small in your code but fills your runtime with all those ifs you aren't writing. If you were to transpile your JS or TS back to pre-ES6 syntax, you'd see all the if clauses that the runtime is going to be doing anyways. Now sure, if the runtime is doing it, it'll be a little faster, but it is still something to watch for. In code reviews, when a developer is being, perhaps, over paranoid, I see stuff like this:

if (evt?.detail?.value) {
const tmpObj = {
abc: evt?.detail?.value?.xyz;
};
doSomething(tmpObj);
}


All of those inside the if clause block are unnecessary. They've already been checked higher up in the if condition. A smart optimizer might clean that up, but better the code not have all of that. With a language that's still changing so often, keeping up with optimizing core features I'd guess is a higher priority over making up for poor coding practice.

The risk is when it is combined with other features that don't account for the return being nullish, such as the spread operator.

const { a, b } = x?.y

If x or y doesn't exist, this blows up with a javascript exception. Much safer to either check the x?.y in an if higher up, or have a default object to spread, such as

const { a, b } = x?.y ?? {}

But my preference is generally the if higher up - when something is missing, it likely means the rest of the code in the method is gonna get skipped or have to do additional, perhaps unneeded, null-checking on its own. One early return can make up for a lot of ifs later on.

Trackbacks

Trackback specific URI for this entry

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Standard emoticons like :-) and ;-) are converted to images.
Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA