Reputation: 33900
In JavaScript undefined
is not a keyword, it is a variable. Sort of special variable. This is known to cause trouble because undefined
could be reassigned. I do not really know why would anyone want to do that, but this is possible, and maybe you can experience this by using one of those genius frameworks out there, see the code:
function f() {
var z, undefined = 42
console.log(z, undefined, z == undefined)
} f()
Outputs:
undefined 42 false
Now how does one protect himself from such a confusion? Should one just cross his fingers that undefined
is undefined?
Upvotes: 0
Views: 570
Reputation: 1720
You can pass undefined as a function parameter, this will ensure that undefined
is undefined
in the scope of the function.
Many JavaScript libraries use this technique, for example look at jQuery source code
//jQuery
(function( window, undefined ) {
...
})( window );
Because the function expects two formal parameters, but we only give it one, the other gets the (true) value undefined
, and then we can rely on that within the function.
Upvotes: 3
Reputation: 938
one possibility is to check the type of the variable instead of checking equality to undefied
:
if (typeof(VARIABLE) != "undefined")
or read on here: How to check for “undefined” in JavaScript?.
Upvotes: 0
Reputation: 140220
Just use void 0
, it's simply bulletproof. And it's a keyword too.
Upvotes: 4