JavaScript null check

afsantos picture afsantos · May 21, 2013 · Viewed 449.2k times · Source

I've come across the following code:

function test(data) {
    if (data != null && data !== undefined) {
        // some code here
    }
}

I'm somewhat new to JavaScript, but, from other questions I've been reading here, I'm under the impression that this code does not make much sense.


In particular, this answer states that

You'll get an error if you access an undefined variable in any context other than typeof.

Update: The (quote of the) answer above may be misleading. It should say «an undeclared variable», instead of «an undefined variable».

As I found out, in the answers by Ryan ♦, maerics, and nwellnhof, even when no arguments are provided to a function, its variables for the arguments are always declared. This fact also proves wrong the first item in the list below.


From my understanding, the following scenarios may be experienced:

  • The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.

  • The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.

  • The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.

Q: Is my understanding correct?


I've tried the following, in Firefox's console:

--
[15:31:31.057] false != null
[15:31:31.061] true
--
[15:31:37.985] false !== undefined
[15:31:37.989] true
--
[15:32:59.934] null != null
[15:32:59.937] false
--
[15:33:05.221] undefined != null
[15:33:05.225] false
--
[15:35:12.231] "" != null
[15:35:12.235] true
--
[15:35:19.214] "" !== undefined
[15:35:19.218] true

I can't figure out a case where the data !== undefined after data != null might be of any use.

Answer

Ry- picture Ry- · May 21, 2013

An “undefined variable” is different from the value undefined.

An undefined variable:

var a;
alert(b); // ReferenceError: b is not defined

A variable with the value undefined:

var a;
alert(a); // Alerts “undefined”

When a function takes an argument, that argument is always declared even if its value is undefined, and so there won’t be any error. You are right about != null followed by !== undefined being useless, though.