The delete
not a guy, but a operator that removes a property from an object. However, it will only work on properties that have the property attribute [[Configurable]]
defined as true
. Behold:
const obj = {};
obj.name = 'Luiz';
Object.defineProperty(obj, 'lastName', {
enumerable: true,
configurable: false // Não irá permitir que deletemos a propriedade `lastName`.
});
console.log(obj);
delete obj.name;
delete obj.lastName;
console.log(obj);
In normal Javascript mode, if you try to delete a non configurable property, false
will be returned. However, if you are on strictly speaking, an error will be cast:
'use strict';
const obj = {};
Object.defineProperty(obj, 'lastName', {
enumerable: true,
configurable: false
});
delete obj.lastName; // Uncaught TypeError: Cannot delete property 'lastName'
That operator will return true
in all cases, except when you try to remove a non configurable property without being in strict mode - we have already seen that, in the latter case, an error is launched.
If, even in strict mode, you want to receive a boolean false
if you were unable to delete the property, you can use the method Reflect.deleteProperty
, entered in Ecmascript 2015 (ES6):
'use strict';
const obj = {};
obj.name = 'Luiz';
Object.defineProperty(obj, 'lastName', {
enumerable: true,
configurable: false
});
console.log(obj);
console.log(Reflect.deleteProperty(obj, 'name')); // true
console.log(Reflect.deleteProperty(obj, 'lastName')); // false
console.log(obj);
It is worth saying that both delete
how much Reflect.deleteProperty
will return true
even if the property you try to delete does not exist.
To deepen on the operator delete
, is worth reading the article "Understanding delete". More advanced details and algorithm can be found in specification.
References on the intenet have a number: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/delete. Here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
– LeAndrade