JavaScript: different behavior when using dot notation and parentheses

This piece of JavaScript code

var x = window.foo; window.x = null; alert( window.bar === undefined ); 

warns "true".

However this fragment

 var x = window.foo; window[x] = null; alert( window.bar === undefined ); 

warns "false".

What's going on here?

(I run this code in the latest Chrome browser inside the HTML page without any other JavaScript code in it.)

Update

As @elusive cleverly summed up in my comment below, I mistakenly assumed that window.x and window[x] equivalent. This is not true. window.x equivalent to window["x"] .

+4
source share
2 answers

The behavior you experience is related to the fact that the undefined property of the Global object is changed to any implementation based on ECMAScript 3. (recent versions of Chrome use ES5, but this behavior is still present).

Consider the second fragment:

 var x = window.foo; window[x] = null; alert( window.bar === undefined ); 

The variable x will contain the value undefined , since the foo property does not exist.

By setting window[x] = null , you override the value of the undefined property:

 window[x] = null; // is equivalent to window['undefined'] = null; // or window.undefined = null; // 

(In your first snippet, when you assign window.x = null , you create a property named "x" on the window object.)

Therefore (in the second fragment), the undefined property will contain null , and window.bar will window.bar undefined :

 alert( window.bar === undefined ); // false alert( undefined === null ); // false 

The undefined property is not specified as { ReadOnly } in ECMAScript 3 (with its friends NaN , Infinity ).

This has changed in ECMAScript 5, these properties are described as non-writable.

+3
source
 var x = window.foo; // set the local variable x to the contents of window.foo window.x = null; // set property x on window to null 

Here you directly set the x property to null.

 var x = window.foo; // set the local variable x to the contents of window.foo window[x] = null; // set they key with the value of x to null 

Here you set the property using it as key in the window object. What key? Well, that depends on the value of x , if x is bar , you really will do window.bar = null , if x is blub , you will do window.blub = null .

For more information about this, you should go to MDC:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators

+1
source

All Articles