What is the delete Operator in JavaScript?
Overview
JavaScript developers often wonder what the delete operator even is. What is it used for? Why do we use JavaScript's delete operator? The delete operator is one of the most underutilized JavaScript operators and that's what we're going to fix right now.
The javascript delete operator is used to remove an element from an array, objects, and properties from an object. It's important to note that the javascript delete operator is not a method; it's a statement.
Syntax
- Syntax to delete an object.
- Syntax to delete the property of an object.
- Syntax to delete element from an array.
Description
After removing the property from the object or array element, the javascript delete operator returns true. Even if no property or index could be found in the object or array, it still returns true. Only when you attempt to delete variables and functions does it return false.
Non-configurable Properties
When you set configurable as false for a property, the delete operator returns false.
Strict Vs. Non-strict Mode
strict mode is used to write secure JavaScript. Deleting a property in strict mode will result in an error because the delete operator is prone to errors.
Can We Delete Variables in Javascript?
No, is the response. The javascript delete operator does not allow us to delete variables because they are not configurable like objects. The remove operator will return false if you do that.
Examples
Delete and the Prototype Chain
Only the object's own properties are deleted using the delete operator. The properties of an object's prototype are unaffected. Deleting a property that is not owned by the object also has no effect but does return true.
Example:
Deleting Array Elements
Same as object properties, we can also delete elements of an array with the javascript delete operator. It will return true even if the index is not found.
Browser Compatibility
The javascript delete operator is supported by the following popular browsers.
Browser | Full support |
---|---|
Chrome | Yes |
Edge | Yes |
Firefox | Yes |
Opera | Yes |
Safari | Yes |
Samsung Internet | Yes |
Android Webview | Yes |
Deno | Yes |
Node.js | Yes |
Conclusion
- The javascript delete operator can be really useful when you want to remove an object, the property of an object, or an element from a JavaScript array.
- delete is not a method but a statement.
- However, there are some things that you need to be aware of so that you don't cause any bugs by using them incorrectly.
- This article should have cleared up some of the mystery surrounding this operator and how it works in JavaScript.