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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (1)

Collapse
 
jarrell_harewoodmbpss_88 profile image
Jarrell Harewood MBPsS

Hi Wenrei, great post!

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up