It appears that window.undefined
is writable, i.e. it can be set to something else than its default value (which is, unsurprisingly, undefined
).
The "standard" solution to this problem is to use the built in void
operator. Its only purpose is to return undefined:
var my_undefined = void 0;
In addition to this, yhere are other ways to get undefined
:
Functions return undefined if you don't return
anything so you could do something like
this_is_undefined = (function(){}());
You also get undefined if you don't pass enough arguments to a function. So a common idiom is
function foo(arg1, arg2, undefined){ //undefined is the last argument
//Use `undefined` here without worrying.
//It is a local variable so no one else can overwrite it
}
foo(arg1, arg2);
//since you didn't pass the 3rd argument,
//the local variable `undefined` in foo is set to the real `undefined`.
This kind is particularly good for cases when you define and call the function at the same time so you don't have any risk of forgetting and passing the wrong number of arguments latter.