Why does javascript distinguish destination with or without declaration when deleting?

Run the following code in a global context:

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

Both x and y are properties of the global object. Why should javascript distinguish them to some extent?


Easy to follow routine, observing ES5 standard operator delete and internal method object [[delete]] .

A more expressed question is why is the other [[configurable]] attribute used?

+6
source share
1 answer

Have a look at the second answer in this related kangax question .

var x = 1 declares a variable x in the current scope (for example, execution context). If a declaration appears in the function, the local variable is declared; if it is on a global scale, a global variable is declared.

x = 1, on the other hand, is simply an assignment of a property. First, it tries to resolve x in a chain of chains. If he finds it anywhere in this chain of domains, it performs the assignment; if it does not find x, then it only creates the x property for the global object (which is the top level object in the scope chain).

Now notice that it does not declare a global variable; it creates a global property.

The difference between the two is subtle and can be confusing if you do not understand that variable declarations also create properties (only for a Variable object) and that each property in Javascript (well, ECMAScript) has certain flags that describe their properties - ReadOnly, DontEnum and DontDelete.

Since a variable declaration creates a property with the DontDelete flag, the difference between var x = 1 and x = 1 (when executed in the global area) is that the former unambiguous declaration creates a DontDelete'able property, and the latter does not. As a result, the created property through this implicit assignment can then be deleted from the global object and the former - the one that is created by declaring a variable - cannot be.

+5
source

Source: https://habr.com/ru/post/948608/


All Articles