I’m reviewing a plain JS code base


I’m reviewing a plain JS code base. It contains over 1,000 uses of optional chaining: “?.”

Why? Because they don’t feel they can trust the properties will exist, so they defensively add “?.” everywhere.

This is unfortunate. It infers we have no idea whether any property will exist, when in actuality, the app requires most properties to operate, and will fail in unexpected ways if a property is missing.

The solution? Standardize responses fetched via HTTP.

Here's two approaches if the app requires a property that's missing in an HTTP response:

1. Fix it in the HTTP response handler by adding a logical default.
2. Throw an error in the HTTP response handler so the app fails quickly. Zod is helpful for validating HTTP responses.
Side note: This is why I was against adding optional chaining to JS. I was afraid it would lead to abuses like this.

Optional chaining is useful, but usage should be rare. Using optional chaining everywhere "just-in-case" leads to "noisier", ambiguous code, that fails slowly.

View original on X