Why Can’t You Delete var‑Declared Globals in JavaScript?
JavaScript global variables can be created either explicitly with var or implicitly without it, but only the implicit globals are deletable; this article explains the underlying property descriptor differences, demonstrates delete behavior, and shows how to modify configurability using Object.defineProperty.
In JavaScript, there are two ways to declare global variables.
Explicit global variable declared with var
Implicit global variable declared without var
The difference lies in whether they can be removed with the delete operator.
Consider the following code:
var a = 'a'; // explicit global
b = 'b'; // implicit global
console.log(a); // a
console.log(b); // b
console.log(window.a); // a
console.log(window.b); // bIn JavaScript, global variables are properties of the global object ( window), so both can be accessed via window.
Attempt to delete them:
// Explicit global cannot be deleted
delete a; // returns false
// Implicit global can be deleted
delete b; // returns true
// Deletion results
console.log(typeof a); // string
console.log(typeof b); // undefinedThe delete operator can remove an object’s property unless the property is non‑configurable; in strict mode it throws an exception.
This means variables declared with var are non‑configurable. You can verify this with Object.getOwnPropertyDescriptor:
Object.getOwnPropertyDescriptor(window, a);
// {value: "a", writable: true, enumerable: true, configurable: false}
Object.getOwnPropertyDescriptor(window, b);
// {value: "b", writable: true, enumerable: true, configurable: true}The fundamental difference is that explicitly declared globals are non‑configurable and cannot be deleted.
Note that once a property’s configurable attribute is set to false, its descriptor cannot be changed, so you cannot make an explicit global deletable by altering its descriptor; conversely, you can make an implicit global non‑deletable by setting configurable to false:
b = 'b';
var descriptor = Object.getOwnPropertyDescriptor(window, b);
descriptor.configurable = false;
Object.defineProperty(window, b, descriptor);
delete b; // returns falseSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
