Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 dont understand what's mean the non-configurable. Why I can't delete the y?

like image 494
PumpkinSeed Avatar asked Dec 09 '22 03:12

PumpkinSeed


1 Answers

When you add a property to an object, you can make it configurable or non-configurable. The long hand version of your example:

x = 42;

Is

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

Configurable properties can be deleted, which removes them from the object (this may then lead to the memory being recovered, but it is not direct).

You could also write:

window.x = 42;

Which makes it more obvious when we come to the next issue.

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

And this is the real reason you can't delete y. It isn't a property and it isn't attached to an object. The delete keyword is for deleting a property from an object.

In the case of y - it will naturally be available for garbage collection when it cannot be reached (or when the reference count is 0 in older browsers).

You can also prevent properties from being deleted:

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

This will cause either the false return from the attempt to delete it, or an error if you are running in strict mode.

like image 200
Fenton Avatar answered Jan 18 '23 23:01

Fenton