Does JavaScript undefined Equals undefined?

Weird JS

Does "undefined" equals "undefined"?
Does JavaScript "undefined" equals "undefined"?

As you know sometimes JavaScript can be weird. Let’s see the following example and let’s try to answer the question: does “undefined” equals “undefined”. What do I mean?

First take a look at the following code.

var a;
var b = undefined;
// alerts "false"
alert(b == a);

Both a and b are undefined, but they are NOT equal. Now let’s see where it can become a problem.

We have an object with one member variable that is not defined.

var f1 = function()
var obj1 = new f1();

Now you’d like to know whether the object “b” has the property “myvar”. There are lots of examples online, but what’s the right way?


Appearantly the value of b.myvar should be undefined.

alert(obj1.myvar); // undefined

But that doesn’t mean that it is the same value if the object was declared this way:

var f2 = function()
	this.myvar = undefined;
var obj2 = new f2();

This is a completely different thing. Why? In the first case if we try to check whether the property myvar belongs to obj1 we can go wrong with:

if (obj1.myvar) // false

This is false simply because obj1.myvar is undefined

if (obj2.myvar) // false

Again is false, because obj2.myvar is undefined.

The same thing happen when using the other “famous” approach.

if (typeof obj1['myvar'] != 'undefined') // false
if (typeof obj2['myvar'] != 'undefined') // false

Clearly this is not the right answer, becase even it is undefined myvar belongs to obj2!


Now let’s try with hasOwnProperty supported by almost every modern browser.

if (obj1.hasOwnProperty('myvar')); // false
if (obj2.hasOwnProperty('myvar')); // true

Here you can see that when the member variable is explicitly defined as “undefined” the object “has the property” and hasOwnProperty returns true. Yet again, “undefined” does not always equal to “undefined”.

6 thoughts on “Does JavaScript undefined Equals undefined?

  1. Actually you’re right somehow! When I test it with the Firebug console …

    var a;
    var b = undefined;
    alert(a === b);

    … it strangely returns true.
    But within a <script> tag …

    var a;
    var b = undefined;
    alert(a === b);

    is FALSE. Isn’t it weird?

  2. When it runs in firebug console, it alert false. Use console.log(a), it return [a, ,a …]. Here a means the HTMLLinkElements collections

Leave a Reply

Your email address will not be published. Required fields are marked *