Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't understand the behavior of deleting vars in JavaScript

Here is the issue:

var x = 5;
window.x === x // true. x, as it seems, is a property of window
delete x; // false
delete window.x; // false;

BUT

window.x = 5;
delete window.x; // true

AND

window.x = 5;
delete x; // true

What is the explanation for such behavior?

like image 716
Michael Sazonov Avatar asked Mar 21 '23 23:03

Michael Sazonov


1 Answers

Essentially the reason is that declared variables are created with an internal DontDelete attribute, while properties created via assignment are not.

Here is great article explaining the inner details of delete: Understanding delete

When declared variables and functions become properties of a Variable object — either Activation object (for Function code), or Global object (for Global code), these properties are created with DontDelete attribute. However, any explicit (or implicit) property assignment creates property without DontDelete attribute. And this is essentialy why we can delete some properties, but not others:

like image 84
Peter Avatar answered Apr 25 '23 18:04

Peter