JavaScript delete operator is used to remove the property from the object. It does not delete variables or functions. However, deleting an object property that doesn’t exist will not affect the object but will return true.
It can be useful for dynamic manipulation of objects where certain properties may no longer be needed or applicable.
Syntax
Syntax to delete an object property
delete object.property
// or
delete object['property']
Syntax to delete an object
delete objectName
Syntax to delete element from an array
delete arrayName[index]
Parameters
- object: This is the object whose property we want to delete.
- property: This is the property to be deleted.
- objectName: It is the object that needs to be deleted.
- arrayName: This is an array whose element we want to delete.
- index: It is an index of the element that needs to be deleted.
Return value
The delete operator returns true if the specified property is deleted or false if the property is not deleted.
Exceptions
TypeError
Thrown in strict mode if the property is an own non-configurable property.
ReferenceError
Thrown if the object is super.
Visual Representation
Example 1: How to Use the delete operator
let appObj = {a: 21, b: 22, c: 23};
console.log(delete appObj.a);
console.log(appObj);
Output
true
{ b: 22, c: 23 }
You need to keep in mind that the delete operator should not be used on predefined JavaScript object properties. This is because it can crash your application.
Example 2: Delete the whole object
It might be impossible if you try to delete the whole object. This is because it can only remove the properties from the object, not the entire object.
let appObj = {a: 21, b: 22, c: 23};
console.log(appObj);
delete appObj;
console.log(appObj);
Output
{ a: 21, b: 22, c: 23 }
{ a: 21, b: 22, c: 23 }
Example 3: deleting a variable and a function
var myVar = "Hello";
console.log(delete myVar);
function myFunc() {
console.log("Hello from myFunc");
}
console.log(delete myFunc);
Output
false
false
Example 4: Deleting array values using delete
let arr = [1, 2, 3]
console.log(delete arr[0]);
console.log(arr);
Output
[ <1 empty item>, 2, 3 ]
Example 5: Non-configurable Properties
A property is considered non-configurable if its configurable attribute is false. Non-configurable properties have restrictions: they cannot be deleted, and their attributes (except value and writable) cannot be changed.
let obj = {};
Object.defineProperty(obj, 'prop', {
value: 42,
writable: true,
enumerable: true,
configurable: false
});
console.log(obj.prop);
console.log(delete obj.prop);
Output
42
false
Browser Compatibility
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Opera 9 and above
- Safari 1 and above