My node.js application uses numerous json values from an API. For example:
var coins = player.game.coins + player.game2.coins;
You can use logical operators
|| to accomplish this.
var coins = player.game.coins + ((player.game2 && player.game2.coins) || 0);
player may be undefined then you will need to check to ensure that exists before checking
game2. So it'd be
((player && player.game2 && player.game2.coins) || 0)
It makes sense once you realize how the code is evaluated.
&& is the AND operation and so it checks that each value exists from left to right.
player exists AND
player.game2 exists AND
player.game2.coins exists and thus stops the comparison and the value is used. If either of those fail then it goes outside the parenthesis and does the OR which returns
0 for a default value.