The delete operator removes a property from an object.
where expressions are.
- Object – The name of an object, or an expression evaluating to an object.
- Property – The property to delete.
- The property is an own non-configurable which case is true.
- In case false is returned in non-strict mode.
Throws Global_objects/SyntaxError in strict mode if the property is an own non-configurable property.
The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned.
However, it is important to consider the following scenarios:
- If the property which you are trying to delete does not exist, delete will not have any effect and will return true.
- If a property with the same name exists on the object’s prototype chain, then, after deletion, the object will
- use the property from the prototype chain (in other words, delete only has an effect on own properties).
- Any property declared with var cannot be deleted from the global scope or from a function’s scope.
As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression).
- Functions which are part of an object (apart from the global scope) can be deleted with delete.
- Any property declared with let or const cannot be deleted from the scope within which they were defined.
- Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array,
- Object and properties that are created as non-configurable with methods like Object.defineProperty().
delete object properties:
The delete operator will not delete ordinary variables.
To delete “global variables,” since they are actually properties of the global object (window in the browser).
The delete operator also has a return value.
If it succeeds in deleting a property, it will return true.
If it fails to delete a property because the property is unwritable it will return false, or if in strict mode it will throw an error.
This property is marked as non-configurable, delete won’t have any effect, and will return false. In strict mode this will raise a SyntaxError.
var, let and const create non-configurable properties that cannot be deleted with the delete operator:
Strict vs.non-strict mode
- In strict mode, if delete is used on a direct reference to a variable, a function argument or a function name, it will throw a SyntaxError.
- If any variable defined with var is marked as non-configurable.
- Here example, salary is non-configurable and cannot be deleted.
- In non-strict mode, the delete operation will return false.
The same code behaves in strict mode. Instead of returning false, the statement raises a SyntaxError.
delete and the prototype chain
we are delete an own property of an object while a property with the same name is available on the prototype chain.