How dangerous is it in JavaScript, really, to assume undefined is not overwritten?

JavascriptUndefined

Javascript Problem Overview


Every time anyone mentions testing against undefined, it's pointed out that undefined is not a keyword so it could be set to "hello", so you should use typeof x == "undefined" instead. This seems ridiculous to me. Nobody would ever do that, and if they did it would be reason enough to never use any code they wrote... right?

I found one example of someone who accidentally set undefined to null, and this was given as a reason to avoid assuming that undefined isn't overwritten. But if they'd done that, the bug would have gone undetected, and I fail to see how that's better.

In C++ everyone is well aware that it's legal to say #define true false, but nobody ever advises you avoid true and use 0 == 0 instead. You just assume that nobody would ever be a big enough jerk to do that, and if they do, never trust their code again.

Has this ever actually bitten somebody where someone else assigned to undefined (on purpose) and it broke your code, or is this more of a hypothetical threat? I'm willing to take my chances to make my code marginally more readable. Is this a really bad idea?

To reiterate, I am not asking for how to protect against reassigned undefined. I've seen those tricks written 100 times already. I'm asking how dangerous it is to not use those tricks.

Javascript Solutions


Solution 1 - Javascript

No, I never have. This is mostly because I develop on modern browsers, which are mostly ECMAScript 5 compliant. The ES5 standard dictates that undefined is now readonly. If you use strict mode (you should), an error will be thrown if you accidentally try to modify it.

undefined = 5;
alert(undefined); // still undefined

'use strict';
undefined = 5; // throws TypeError

What you should not do is create your own scoped, mutable undefined:

(function (undefined) {
    // don't do this, because now `undefined` can be changed
    undefined = 5;
})();

Constant is fine. Still unnecessary, but fine.

(function () {
    const undefined = void 0;
})();

Solution 2 - Javascript

No proper code will do such a thing. But you can never know what some wannabe-smart developer or a plugin/library/script you are using did. On the other side, it's extremely unlikely and modern browsers will not allow overwriting undefined at all, so if you are using such a browser for development you'll quickly notice if any code tries to overwrite it.


And even though you did not ask for it - many people will probably find this question when looking for the more common "how to protect against redefined undefined" issue, so I'll answer that anyway:

There's a very good way to get a truly undefined undefined no matter how old the browser is:

(function(undefined) {
    // your code where undefined is undefined
})();

This works because an argument that is not specified is always undefined. You can also do it with a function that accepts some real arguments, e.g. like this when you are using jQuery. It's usually a good idea to ensure a sane environment in this way:

(function($, window, undefined) {
    // your code where undefined is undefined
})(jQuery, this);

Then you can be sure that inside that anonymous function the following things are true:

  • $ === jQuery
  • window === [the global object]
  • undefined === [undefined].

However, note that sometimes typeof x === 'undefined' is actually necessary: If the variable x has never been set to a value (contrary to being set to undefined), reading x in a different way such as if(x === undefined) will throw an error. This does not apply to object properties though, so if you know that y is always an object, if(y.x === undefined) is perfectly safe.

Solution 3 - Javascript

There's a simple solution to that: compare against void 0 which is always undefined.

Note that you should avoid == as it may coerce the values. Use === (and !==) instead.

That said, the undefined variable may be set by error if someone writes = instead of == when comparing something against undefined.

Solution 4 - Javascript

Only you know what code you use, and therefore how dangerous it is. This question can't be answered in the way you've clarified you want it answered.

  1. Create a team policy, disallow redefining undefined, reserving it for its more popular usage. Scan your existing code for undefined left assignment.

  2. If you don't control all the scenarios, if your code is used outside situations you or your policies control, then obviously your answer is different. Scan the code that does use your scripts. Heck, scan web for statistics of undefined left assignment if you wish, but I doubt that's been done for you, because it's easier to just pursue answer #1 or #3 here instead.

  3. And if that answer isn't good enough, it's probably because, again, you require a different answer. Maybe you are writing a popular library that will be used inside corporate firewalls, and you don't have access to the calling code. Then use one of the other fine answers here. Note the popular jQuery library practices sound encapsulation, and begins:

    (function( window, undefined ) {

Only you can answer your question in the specific way you seek. What more is there to say?

edit: p.s. if you really want my opinion, I'll tell you it's not dangerous at all. Anything that would be so likely to cause defects (such as assigning to undefined, which is obviously a well-documented risky behaviour) is itself a defect. It's the defect that is the risk. But that's just in my scenarios, where I can afford to hold that perspective. As I'd recommend you do, I answered the question for my use-cases.

Solution 5 - Javascript

It's safe to test against undefined. As you already mention. If you get to some code that overrides it (which is highly improvable), just don't use it anymore.

Maybe if you are creating a library for public use, you can use some of the techniques to avoid the user change it. But even in this case, it's their problem, not your library.

Solution 6 - Javascript

You can use undefined in your code when coding for browsers supporting ECMAScript 5.1 as it is immutable according to the language specification.

Also see this compatibility table or this caniuse ECMAScript 5 to see that all modern browsers (IE 9+) have implemented immutable undefined.

Solution 7 - Javascript

It's not dangerous at all. It can only be overwritten when running on an ES3 engine and that's not likely to be used any more.

Solution 8 - Javascript

First of all, if your code breaks it's probably not because some other developer out there "is trying to be a jerk" as you put it.

It's true that undefined is not a keyword. But it is a global level primitive. It was intended to be used like this (see "undefined" at developer.mozilla.org):

var x;
if (x === undefined) {
	// these statements execute
}
else {
	// these statements do not execute
}

The common alternative to that (also from MDN) and in my opinion the better way is:

// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
	// these statements execute
}

if(x === undefined){ // throws a ReferenceError

}

Which has a couple of advantages, the obvious one (from the comments) is that it does not trigger an exception when x is not declared. It's also worth noting that MDN also points out that it is important to use === over == in the first case because:

var x=null;
if (x === undefined) {
	// this is probably what you meant to do
	// these lines will not execute in this case
}
else if (x == undefined) {
	// these statements will execute even though x *is* defined (as null)
}
else {
	// these statements do not execute
}

This is another often overlooked reason why it is probably better to just use the second alternative in all cases.

Conclusion: It's not wrong to code it the first way, and certainly not dangerous. The argument you've seen that you use as an example against it (that it can be overwritten) is not the strongest argument for coding the alternative with typeof. But using typeof is stronger for one reason specifically: it doesn't throw an exception when your var is not declared. It could also be argued that using == instead of === is a common mistake in which case it's not doing what you expected it to. So why not use typeof?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCosmologiconView Question on Stackoverflow
Solution 1 - JavascriptRy-View Answer on Stackoverflow
Solution 2 - JavascriptThiefMasterView Answer on Stackoverflow
Solution 3 - JavascriptLuceroView Answer on Stackoverflow
Solution 4 - JavascriptshannonView Answer on Stackoverflow
Solution 5 - JavascriptBart CalixtoView Answer on Stackoverflow
Solution 6 - JavascriptDaniel A. R. WernerView Answer on Stackoverflow
Solution 7 - Javascriptkirk.burlesonView Answer on Stackoverflow
Solution 8 - JavascriptOctopusView Answer on Stackoverflow