JS: Delete operator

By Xah Lee. Date: . Last updated: .

delete obj[key]

Deletes the property key from obj.

The delete operator never goes up the prototype chain.

delete return true even if property does not exist.

// example of deleting a property
const obj = {"k1":1, "k2":2};
delete obj["k1"];
console.log(obj); // { k2: 2 }
// delete returns true even if property does not exist

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

Note, delete expr just return true if expr is 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]

See also: JS: Reflect.deleteProperty

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

ECMAScript 2015 §ECMAScript Language: Expressions#sec-delete-operator

JS Object Property Topic

  1. JS: Property Overview
  2. JS: Property Key
  3. JS: Property Dot Notation / Bracket Notation
  4. JS: Create/Delete Property
  5. JS: Get Property, Set Property
  6. JS: Check Property Existence
  7. JS: Access Property
  8. JS: Property Attributes, writable, enumerable, configurable
  9. JS: Getter/Setter Properties
  10. JS: Property Descriptor
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon