I like to have somewhat clean code:
var currentVar = aBigObject['Key1']['Key2']['Key3'];
generalValues.push(((!currentVar) ? 0 : currentVar));
The alternative (I think) is this:
if (!aBigObject['Key1']['Key2][Key3']) generalValues.push(0);
else generalValues.push(aBigObject['Key1']['Key2']['Key3']);
To me, the second is unnecessarily long and difficult to read. My question is, is it really safe/good practice to set a variable to something that can potentially be undefined?
It’s perfectly safe in that it’s not going to cause an error. It also means that you don’t have to do all of those lookups again.
Your alternative also seems to make little sense (and certainly isn’t doing the same thing as your first code snippet), as it has a totally different behavior when(The edit to the question fixes this.)aBigObject['Key1']['Key2][Key3']isn’t falsey (assigning it to itself rather than pushing it ongeneralValues).Your first example certainly has lots of unnecessary parens and can be written:
..and could possibly be better written as
Your general point seems to be, “Why is the first snippet using
currentVar?” And the answer is that property lookups are not free. So once you’ve done the lookup ofKey1onaBigObject, andKey2on the result, andKey3on the result of that, you remember and reuse it rather than looking it up again. JavaScript objects are hashmaps, lookups are cheap but they aren’t free. But in that specific case, you can do that another way (see above).