DEV Community

Discussion on: Accessing Nested Objects in JavaScript

Collapse
 
martinhaeusler profile image
Martin Häusler

It's a GOOD thing that you get this error from JS! It tells you that something in your program and/or your data is wrong. By coding like this, you may circumvent the error message, but the root cause still exists. Use Typescript instead. It will tell you exactly when it is safe to navigate nested structures and when it is not. In the latter case, you should HANDLE the error, not ignore it.

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

I agree TypeScript is safe and provides great many flexibilities in handling unexpected code.

But the alternate without a typescript (preference differs) would be to catch all these in a try catch block throughout the code, which will look really messy in a huge codebase. Sometimes, missing data in nested structures might be intentional too, mostly because JS is weakly typed. I think handling all those errors is a little too much effort and rather we should focusing on coding for the problem and let utils/libs handle the language shortcomings.