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
undefinedfor initially undefined values and usingnullwhenever you want to unassign a value a good option? - Using
undefinedeverywhere simplifies things at first, but then there is JSON (onlynullavailable) 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@Inputsyou 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 (
undefinedandnull). 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
undefinedwhenever 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,
nullis 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
undefinedis more a "source code" thing, andnullmore 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
undefinedfor undefined values andnullwhen 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.