If I use delete in Javascript, what is the difference between var x and simple x declaration?

x = 42;         // creates the property x on the global object
var y = 43;     // creates the property y on the global object, and marks it as non-configurable


// x is a property of the global object and can be deleted
delete x;       // returns true

// y is not configurable, so it cannot be deleted                
delete y;       // returns false 

I don't understand what non-configurable means. Why can't I remove y?

+4
source share
5 answers

When you add a property to an object, you can make it custom or non-configurable. An example of the long side of your example:

x = 42;

there is

Object.defineProperty(window, 'x', {
  value: 42,
  writable: true,
  configurable: true,
  enumerable: true
});

Custom properties can be deleted, which removes them from the object (this can lead to memory recovery, but it is not direct).

You can also write:

window.x = 42;

This makes it more obvious when we move on to the next problem.

window.x = 42; // x is a property
var y = 43; // y is not a property

, y. . delete .

y - , , , ( 0 ).

:

Object.defineProperty(window, 'x', {
  value: 42,
  writable: true,
  configurable: false,
  enumerable: true
});

false , .

+7
x = 42

window.x = 42

. window.

var y = 43

" ".

delete x

delete window.x

, , , , delete .

delete .

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

( )

+7

delete . x - , . , y - , , .

0

delete

. delete

0

y , y . delete , . y.

0

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


All Articles