Think about it, you write a plugin or a library (let's name it jsKata) and your code contains checks to see if certain things are undefined.

Here's an example :

if (obj.name === undefined) {
    obj.name = "This object has no name";
  }

This code works well until you include another script (found on an obscure website) and it breaks your previous code. By debugging the code, you see the value of undefined is no more undefined but false.

Yes, I know that you thought it was impossible to define undefined but it is, you just have to write undefined = false.

Redefine undefined

There's two way of redefining undefined and they both use self-invoking functions.

Method 1 : Scope your code

(function(undefined) {
    /* your complete code here */
  })();

As you see, the self-invoking function has one parameter named undefined. At line 3, the self-invoking functions is called without any parameter. It results that the parameter has the value undefined (or it is defined to undefined if you prefer).

Take a look at this javascript :

It will display false and then display undefined even if undefined was globally defined at first.

This is the HTML that goes with it :

You can also execute it here.

Method 2 : Globally redefine undefined

There's another method but I don't like it that much. It redefines undefined but nothing protects it from being badly redefined in another chunk of code.

undefined is a global variable accessible using the global window object. Line 2 defines undefined and line 3 display the value of undefined as false. On line 4, I use a self-invoking function as method 1 does but now, I define the global undefined variable through the global window object.

The HTML of this example :

You can also execute it on jsFiddle.

Other methods

Some commentors pointed me other ways of doing it.

You can use typeof :

typeof undefined == "undefined"

Or you could use void(0), it always returns undefined

undefined === void(0) // this returns true

comments powered by Disqus