JavaScript Delete Operator: Properties vs Variables
The JavaScript delete operator is designed to remove own
properties from objects, returning true on successful
deletion and freeing up that property reference. However, when used on
bare variables declared with var, let, or
const, the delete operator does not work,
resulting in either a silent failure returning false or a
compile-time SyntaxError depending on whether strict mode
is enabled.
Deleting Object Properties
The primary purpose of the delete operator is to mutate
an object by removing a specific key-value pair.
const user = {
name: "Alice",
age: 30
};
delete user.age; // returns true
console.log(user); // Output: { name: "Alice" }Key behaviors with object properties include: * Configurable
Properties: By default, standard properties added to an object
are configurable and can be deleted successfully. *
Non-Configurable Properties: Properties configured with
configurable: false using
Object.defineProperty() cannot be removed. In non-strict
mode, delete returns false. In strict mode
("use strict"), it throws a TypeError. *
Prototype Inheritance: The delete operator
only removes an object’s “own” properties. If an object inherits a
property from its prototype chain, deleting it on the instance will not
affect the prototype or the inherited value.
Deleting Bare Variables
The delete operator does not delete variable
declarations created using var, let,
const, or function declarations.
In Non-Strict Mode
Attempting to delete a declared variable fails silently and returns
false:
var x = 10;
let y = 20;
const z = 30;
delete x; // returns false
delete y; // returns false
delete z; // returns false
console.log(x, y, z); // Output: 10 20 30Variables declared in JavaScript create non-configurable bindings in
their respective lexical environments or execution contexts, preventing
the delete operator from removing them.
In Strict Mode
In strict mode, using the delete operator on a direct
variable name (an unqualified identifier) is illegal syntax:
"use strict";
let count = 5;
delete count; // SyntaxError: Delete of an unqualified identifier in strict mode.Implicit Global Variables Exception
In legacy, non-strict JavaScript, assigning a value to an undeclared
variable creates an implicit global property on the global object (e.g.,
window in browsers or global in Node.js):
// Non-strict mode
implicitGlobal = 42;
delete implicitGlobal; // returns true
console.log(typeof implicitGlobal); // Output: "undefined"Because implicitGlobal was not formally declared with
var, let, or const, the engine
adds it as a standard configurable property on the global object rather
than an immutable environment binding, allowing delete to
remove it.