DEV Community

wenrei
wenrei

Posted on

Null/Undefined Check

In react, if we declare and do not initialise a variable, it would be undefined

var a; //undefined
Enter fullscreen mode Exit fullscreen mode

If we would want to assign a variable and initialise a variable later, we could first assign it as null. (Not recommended)

var a = null;
Enter fullscreen mode Exit fullscreen mode

As undefined and null is different, we should perform validation whenever we think that the code would break if the variable is null or undefined.

typeof null          // "object" (not "null" for legacy reasons)
typeof undefined     // "undefined"
Enter fullscreen mode Exit fullscreen mode

To make the code reusable, we could define a utility function to perform the validation. The function could be as simple as a function that takes in any type of input, or a function that utilise Generics.

function nonNullish(value: unknown): boolean {
    return value !== (null || undefined) ? true : false;  
}


function assertNonNullish<TValue>(value: TValue): boolean {
    return value !== (null || undefined) ? true : false;  
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jarrell_harewoodmbpss_88 profile image
Jarrell Harewood MBPsS

Hi Wenrei, great post!