I don't know of a singular, definitive answer on this, but here's a look a some of the language design concerns which provide a partial explanation of the mechanics & considerations at play here.
First and foremost: comparable values like null
, true
and false
are reserved words. These are fundamental parts of the JavaScript language - on a similar level to if
and for
. undefined
seems an awful lot like null
, so it's reasonably intuitive to think they'd be the same in terms of usage. It ends up being a bit different - more like NaN
in this particular regard.
When asking this question, it's worth asking just how much is, in fact, mutable. Practically everything - if you want to override any standard constructor or function, you probably can. Array
, Math
, eval
etc can all be set.
There was no mechanism in the original language to even make a property on the window immutable. Even if the designer thought it would be a good idea to prevent changes to undefined
there was as of yet no means to do so other than changing its syntactic meaning within the language.
These days though, the core language specification offers much more control over how and why a variable can be changed. ECMAScript 5 added in ways to control how properties are mutable, and whether or not a variable is writable
can be configured. This can be seen via the Object.getOwnPropertyDescriptor
function. I believe the only non-writable values on window which might be considered "core JavaScript" are undefined
, Infinity
and NaN
(other values are non-writable in a browser, but I believe they are almost all related to the browser itself, and are not fundamental to the language). Section 15.1.1 of the specification has the details on this; I could find nothing similar in the original spec.
This still doesn't prevent you entirely from "overriding undefined" - if you're not in the global scope, you can treat it as a variable. So, this will simply print undefined
when executed in the global scope -
var undefined = 5;
console.log(undefined);
But this will print 5 -
(function() {
var undefined = 5;
console.log(undefined);
})();
This doesn't change the value at all, it just creates a new local reference to a variable called "undefined". Since the value is defined on the top-level scope (window
), the language only prevents assignment to that specific property on that one specific object.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…