JS: Delete operator

By Xah Lee. Date: . Last updated: .

Deletes the property key from obj.

The delete operator never goes up the prototype chain.

delete return true if:

Return false when key exist but deletion failed. [see JS: Property Attributes, writable, enumerable, configurable]

const obj = {x:1};
delete obj.x;

console.log (
obj.hasOwnProperty ("x") === false
); // true

Example: of property does not exist:

const obj = {};
console.log ( delete obj.k );
// true

Example of failure due to frozen object:

const obj = {p: 1};
Object.freeze ( obj );

console.log (
delete obj.p === false
); // true

console.log (
obj.hasOwnProperty ("p")
); // true

Example of not a object:

console.log ( delete 3 ); // true

Note: do not use delete operator to delete array element. That results a sparse array.

[see JS: Sparse Array]

Use Array.prototype.splice to delete elements in array.

[see JS: Array.prototype.splice]

Note, avoid deleting or adding properties to object. Because, due to implementation, adding/deleting properties is inefficient. Instead, change the value to null.

Reflect.deleteProperty

Use Reflect.deleteProperty instead. It returns false if delete failed.

[see JS: Reflect.deleteProperty]

JS Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials