6

Execute the code below in the global context:

var x = 1;
y = 1
delete x //false
delete y //true

Both x and y is property of global object. Why javascript have to distinguish them in some extent?


It's easy to follow the routine accoring to ES5 standard the delete operator and the the object internal method[[delete]].

The more clear question expressed is that why the different [[configurable]] attribute they adopt ?

yuan
  • 2,434
  • 1
  • 21
  • 29
  • @FelixKling Hi,see you again! But I'm not understand why they have the different `[[configurable]]` attribute. You know I read the standard but didn't find any proof for that. Such decision is driven by? – yuan Jul 03 '13 at 08:23
  • Well I cannot tell you that, I didn't make that decision :) Maybe you should contact someone working on the ECMAScript standard. – Felix Kling Jul 03 '13 at 10:54

1 Answers1

5

Look at the second answer in this related question by kangax.

var x = 1 declares variable x in current scope (aka execution context). If declaration appears in a function - local variable is declared; if it's in global scope - global variable is declared.

x = 1, on the other hand, is merely a property assignment. It first tries to resolve x against scope chain. If it finds it anywhere in that scope chain, it performs assignment; if it doesn't find x, only then it creates x property on a global object (which is a top level object in a scope chain).

Now, notice that it doesn't declare global variable, it creates a global property.

The difference between two is subtle and might be confusing unless you understand that variable declarations also create properties (only on a Variable Object) and that every property in Javascript (well, ECMAScript) have certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.

Since variable declaration creates property with DontDelete flag, the difference between var x = 1 and x = 1 (when executed in global scope) is that former one - variable declaration - creates DontDelete'able property, and latter one doesn't. As a consequence, property created via this implicit assignment can then be deleted from the global object, and former one - the one created via variable declaration - can not be.

Community
  • 1
  • 1
  • This is also sort of documented here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete – elclanrs Jul 03 '13 at 08:06