Raphaël Ferrand

Defensive coding in Javascript

Wed, December 1, 2021

Recent evolutions of Javascript have brought some real cool and useful features, actionable every day.

One that I keep using lately and I’ve been recommanding a few times in my code review is the combination “optional chaining ( ?. )” + “Nullish coalescing operator ( ?? )”:

For example I’ve seen in our codebase something like:

I’ve stumbled upon this today whith some deeply nested objects. A potential issue happening when we want to use the value of a property located deep within a chain of connected objects, like in our example. We do have to check (as we did in our example using a ternary operator), to avoid it to throw an error

Error: can't access property "unsavedChanges", component.emailLocalizationComponent is undefined`.

So let’s see 3 possibilities:

let unsavedEmailLocalization =
  component.emailLocalizationComponent.unsavedChanges;
let unsavedEmailLocalization = component.emailLocalizationComponent
  ? component.emailLocalizationComponent.unsavedChanges
  : false;
let unsavedEmailLocalization =
  component?.emailLocalizationComponent?.unsavedChanges ?? false;

This way we have a concise way to both:

What about support: if you don’t need to support IE then you’re fine. If you do … well …that’s a pity 😅