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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With