I just recently started refactoring my large scale angular app to Typescript's strict mode. Dealing with lots of null checks the question arose again if I should prefer using undefined
over null
or vice versa. A couple of thoughts:
- Is using
undefined
for initially undefined values and usingnull
whenever you want to unassign a value a good option? - Using
undefined
everywhere simplifies things at first, but then there is JSON (onlynull
available) and API responses. How to best deal with those? - How to best deal with pre-checks for when you are reasonably confident that a value is not
null
, but it theoretically could be (e.g. angular@Inputs
you always assign)? Do you prefer to typecast or do you use error checks?
I wonder how do you deal with the problem. Do you prefer one over the other? Do you use both? What's your take on it?
I think the complexity people see comes from a lose definition of those two (
undefined
andnull
). They do not represent the same thing. An empty array is different from an undefined array, and it is also different from an array with a null value in one position. In those cases, those definitions get more clear. And I think the best approach is just to use what the values mean.So, I would use
undefined
whenever a variable has not been assigned yet, or when a method or function does not return anything (exactly how the language behaves on runtime).On the other hand,
null
is used when you explicitly say that variable points to no value. You know that variable exists, but you have nothing to assign to it.I would say
undefined
is more a "source code" thing, andnull
more of a runtime thing.Angular manages state in a very complex and imperative way, in my opinion, which makes checking values harder. But I would use
undefined
for undefined values andnull
when I've passed the point where I would assign a value and I had nothing. If it is a collection, I would just initialize it without values.But I don't think there is a silver bullet answer. Each case should be dealt diferently.