delete object // or delete object.property // or delete object['property']
Parameter: It does not take any parameter.
Return type: This operator returns true if it removes a property. While deleting an object property that doesn’t exist will return a true but it will not affect the object. Though while trying to delete a variable or a function will return a false.
Below are examples of the delete Operator.
Example 2: Assuming an object called person has three key-value pairs (i.e. first name, lastName and phone). Now, using the delete operator to delete the phone property will return true.
As the above picture shows, delete person.phone returns true and logging the person object shows that the phone property doesn’t exist anymore.
Let’s try applying the delete operator for deleting a variable and a function.
Because the delete operator doesn’t work for variables or function, it returns false and the actual variables and functions remain untouched.
Another thing to keep in mind is that this operator doesn’t delete property value rather the property itself.
As objects are reference types, so both the person.phone and phone variable will refer to the same memory address.
The output shows that the delete operator has deleted the property but the value still exists on the memory.
Exception: Global variables can be removed using the delete operator. Because the global variables are properties of the window object and as delete works on objects, it’ll delete the variable.
Without using the var, let or const keyword sets the variable as a global variable and it’ll work as an object property.
true Uncaught ReferenceError: toDelete is not defined
The delete toDelete returns true and trying to access the variable after deleting it throws a reference error as the variable is not defined anymore.
So, using pop(), shift(), or splice() methods is clearly a better approach to deleting array elements.
Conclusion: There are other ways used by developers, such as setting the value of an object property to null or undefined. But the property will still exist on the object and some operators like for in loop will still show the presence of the null or undefined property.
Using the delete property in loops slows down the program significantly. So, this method should only be used when it is absolutely necessary to delete an object property.