Question

19.

What is the delete Operator in JavaScript

Answer

The delete operator in JavaScript is used to remove a property from an object. When you delete a property, the object no longer has that property. However, it's important to note that delete does not affect the prototype chain; if the object inherits a property from its prototype, after deletion, the object will still have access to that property through the prototype chain.

Syntax

delete object.property;

or

delete object['property'];

Here, object is the name of the object, and property is the property you want to delete.

Key Points

  • The delete operator returns true if the operation is possible; it returns false if the operation is not possible (e.g., if the property is non-configurable).
  • delete can only remove properties from objects. It has no effect on variables or functions.
  • delete does not directly free memory. However, if the deleted property was the only reference to an object, it becomes eligible for garbage collection, provided there are no other references to that object.
  • Deleting an array element does not change the array's length, even though the element is no longer in the array. It leaves a hole in the array, making the element at that index undefined.

Examples

Deleting an Object Property

let myObj = {name: "John", age: 30};
delete myObj.age;
console.log(myObj); // Output: { name: "John" }

Attempting to Delete a Non-configurable Property

const obj = {};
Object.defineProperty(obj, 'prop', {
  value: 10,
  configurable: false // prop cannot be deleted
});

console.log(delete obj.prop); // Output: false
console.log(obj.prop); // Output: 10

Deleting an Array Element

let myArray = [1, 2, 3];
delete myArray[1];
console.log(myArray); // Output: [1, undefined, 3]
console.log(myArray.length); // Output: 3

Limitations and Considerations

  • Deleting properties that do not exist does not throw an error; it returns true.
  • delete is not allowed in strict mode when used on undeclared variables.
  • Using delete on an array leaves undefined holes in the array. Use array methods like splice for removing elements if you need to avoid these holes.
  • delete has no effect on variables declared with var, let, or const.
  • It's generally a good practice to avoid using delete for optimizing performance, especially in high-performance applications, as it can potentially slow down future access to object properties.

Support us ❤️

Buy Us A Coffee