This JavaScript snippet
var x = window.foo;
window.x = null;
alert( window.bar === undefined );
alerts “true”.
However, this snippet
var x = window.foo;
window[x] = null;
alert( window.bar === undefined );
alerts “false”.
What is going on here?
(I am running this code in the latest Chrome browser inside a HTML page with no other JavaScript code in it.)
Update
As @elusive cleverly summed up in his comment below, I mistakingly assumed that window.x and window[x] are equivalent. That is not correct. window.x is equivalent to window["x"].
The behavior that you are experiencing is because the
undefinedproperty of the Global object, is mutable on any ECMAScript 3 based implementation. (latest Chrome versions are implementing ES5, but this behavior is still present).Let’s examine the second snippet:
The
xvariable will hold theundefinedvalue, since thefooproperty does not exist.By assigning
window[x] = null, you are overriding the value of theundefinedproperty:(In your first snippet, when you assign
window.x = null, you are creating a property named"x"on thewindowobject.)Therefore (in your second snippet), the
undefinedproperty will holdnull, andwindow.barwill produceundefined:The
undefinedproperty was not specified as{ ReadOnly }on ECMAScript 3, (along with his friendsNaN,Infinity).This has changed in ECMAScript 5, those properties are described as non-writables.