JS: “delete” Operator
delete obj[key]
-
Deletes the property key from obj.
Returntrue
when:
- Property exist and is deleted.
- Property does not exist.
- Argument is not an object.
else return
false
. 〔see Property Attributes〕💡 TIP: The
delete
operator never goes up the Prototype Chain.// example of using delete operator const jj = { kk: 1 }; delete jj.kk; console.log(jj.hasOwnProperty("kk") === false);
// Example of not a object console.log((delete 3) === true);
// example of property does not exist const jj = {}; console.log((delete jj.k) === true);
// example of failure due to frozen object const jj = { p: 1 }; Object.freeze(jj); // console.log((delete jj.p) === false); // error: Uncaught TypeError: Cannot delete property 'p' of #<Object> console.log(jj.hasOwnProperty("p"));
delete obj.key
-
similar to
delete obj[key]
. 〔see Property Dot Notation vs Bracket Notation〕
💡 TIP: Never Use the Delete Operator
- Do not use
delete
operator to delete array element. That results a Sparse Array . Use Array.prototype.splice to delete elements in array. - Delete operator should only be used to delete object property. But Reflect.deleteProperty is better, because it has more sensible return value.
- Avoid deleting or adding properties to object frequently, as in a loop. Because, due to implementation, adding/deleting properties is inefficient. Instead, change the value to null.