0

I occasionally write JavaScript, and this JavaScript is invariably littered with bugs. These often boil down to accessing undefined attributes on objects. However JavaScript engines seem very unwilling to error out; instead of falling over my applications stumble on for as long as possible, propagating undefined values through their state and misbehaving in subtle ways. By the time there is an obvious symptom it often manifests in totally separate component from the actual error (which is sometimes just a typo!).

This is obviously a deliberate and sensible design choice given JavaScript's use-cases, but when developing it's a pain. Are there any techniques for getting my code to fall honourably off its horse in the event of undefined accesses, so that I can help it get back on again?

Brendan
  • 1,995
  • 1
  • 20
  • 35
  • 2
    In my opinion that's one of the many reasons why things like Typescript https://www.typescriptlang.org exist, which prevent those things from happening though type checks at compile time – Andreas Müller Jan 19 '19 at 11:36

1 Answers1

1

What your describing is type checking. These days, the two most popular type-checking options when it comes to JavaScript are TypeScript (which @AndreasMüller already recommended above) and Flow. Using either of these should help you avoid accessing undefined object properties, and more code smells/issues. To get started with TypeScript, check out TypeScript in 5 minutes.

Itai Steinherz
  • 777
  • 1
  • 9
  • 19
  • I disagree that I'm describing type checking; having failed attribute lookups raise an error is much less intensive than that! But thanks for the pointer, it sounds like TypeScript would really help. – Brendan Jan 20 '19 at 10:22