DEV Community

Discussion on: How do you deal with null vs undefined?

Collapse
 
merri profile image
Vesa Piittinen • Edited

I guess the biggest consideration is this:

// a React example, but simple enough :)
function ShowProgress({ data = loadingStateData }) {
    if (data == null) {
        return <LoadingFailed />
    }
    return <Component data={data} />
}

Whether actually doing logic like this is a good idea or not is up to the reader (one might argue it is "confusing"), but default values is the biggest gotcha with undefined since defaults fill always override it when passing to functions or when destructuring. In those cases null will stay.

So essentially every time you want to indicate you couldn't get a value it is safer to indicate that as null, because undefined may be overridden by a default value. Personally I like to deal with them as equal by using == null comparison. And I dislike applying strict typing to JS so I don't need to waste time telling computer what things are. Instead I force type to whatever is needed, such as using ~~variable to force variable as integer Number that is never NaN, or check that the type matches expectation. This has the benefit of working in runtime as well (unlike TypeScript which doesn't help you with unexpected runtime issues).