Often I encounter code that resembles the following hypothetical example:
if (node.data.creatures.humans.women.number === Infinity) {
// do-something
}
The issue arises when the node is undefined, causing this condition to fail. Similarly, it will fail if node.data, node.data.creatures, and so on are also undefined.
To prevent these errors, I find myself resorting to lengthy conditional statements like this one:
if (node && node.data && node.data.creatures && node.data.creatures.humans && node.data.creatures.women && node.data.creatures.humans.women.number === Infinity) {
// do-something
}
Not only does this make the code harder to read, but if different parts of the JSON object need to be accessed multiple times in the code, things can quickly become messy.
Is there a better way to handle errors such as "Cannot call property of undefined" caused by situations like the one described above? How do you approach dealing with these kinds of scenarios?