How to check for an undefined or null variable in JavaScript?

I think the most efficient way to test for “value is null or undefined” is

if ( some_variable == null ){
  // some_variable is either null or undefined
}

So these two lines are equivalent:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

check for optional arguments:

function(foo){
    if( foo == null ) {...}

check for properties on an existing object

if(my_obj.foo == null) {...}

On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

Note 2

This – even shorter – variant is not equivalent:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

Note 3

In general it is recommended to use === instead of ==.
The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only
exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

EDIT 2021-03:

Nowadays most browsers
support the Nullish coalescing operator (??)
and the Logical nullish assignment (??=), which allows a more concise way to
assign a default value if a variable is null or undefined, for example:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

can be written as any of these forms

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;

Leave a Comment