JavaScript The delete operator


Example

The delete operator deletes a property from an object.

Syntax:

delete object.property

delete object['property']

Returns:

If deletion is successful, or the property did not exist:

  • true

If the property to be deleted is an own non-configurable property (can't be deleted):

  • false in non-strict mode.
  • Throws an error in strict mode

Description

The delete operator does not directly free memory. It can indirectly free memory if the operation means all references to the property are gone.

delete works on an object's properties. If a property with the same name exists on the object's prototype chain, the property will be inherited from the prototype.
delete does not work on variables or function names.

Examples:

// Deleting a property
foo = 1;              // a global variable is a property of `window`: `window.foo`
delete foo;           // true
console.log(foo);     // Uncaught ReferenceError: foo is not defined

// Deleting a variable
var foo = 1;
delete foo;           // false
console.log(foo);     // 1 (Not deleted)

// Deleting a function
function foo(){ };
delete foo;           // false
console.log(foo);     // function foo(){ } (Not deleted)

// Deleting a property
var foo = { bar: "42" };
delete foo.bar;       // true
console.log(foo);     // Object { } (Deleted bar)

// Deleting a property that does not exist
var foo = { };
delete foo.bar;       // true
console.log(foo);     // Object { } (No errors, nothing deleted)

// Deleting a non-configurable property of a predefined object
delete Math.PI;       // false  ()
console.log(Math.PI); // 3.141592653589793 (Not deleted)