Time and again I have to deal with code like consider following hypothetical example:
if (node.data.creatures.humans.women.number === Infinity) {
// do-something
}
The problem is that if the node is undefined, this condition will break. Similarly, it will break if node.data is undefined, node.data.creatures is undefined, and so on.
So I end up using following kind of long condition:
if (node && node.data && node.data.creatures && node.data.creatures.humans && node.data.creatures.women && node.data.creatures.humans.women.number === Infinity) {
// do-something
}
Now, imagine I have to use parts of that JSON object in many other parts of code too. The code suddenly starts looking very ugly.
Is there another way of avoiding errors like "Cannot call property of undefined", etc., due to the first condition I mentioned (such that the code looks better too)?
How do you deal with such situations?