Frontend Development 3 min read

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.

JavaScript
JavaScript
JavaScript
Why Can’t You Delete var‑Declared Globals in JavaScript?

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:

<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); // b</code>

In JavaScript, global variables are properties of the global object (

window

), so both can be accessed via

window

.

Attempt to delete them:

<code>// 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); // undefined</code>

The

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

:

<code>Object.getOwnPropertyDescriptor(window, a);
// {value: "a", writable: true, enumerable: true, configurable: false}
Object.getOwnPropertyDescriptor(window, b);
// {value: "b", writable: true, enumerable: true, configurable: true}</code>

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

:

<code>b = 'b';
var descriptor = Object.getOwnPropertyDescriptor(window, b);
descriptor.configurable = false;
Object.defineProperty(window, b, descriptor);
delete b; // returns false</code>
JavaScriptglobal variablesproperty descriptorvardelete operator
JavaScript
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.