JS: delete (operator) ❌
delete obj[key]-
- Deletes the property key from obj.
- Return
truewhen: - Property exist and is deleted.
- Property does not exist.
- Argument is not an object.
else return
false.🛑 WARNING: using delete operator on array results a Sparse Array.
🟢 TIP: The
deleteoperator never goes up the Prototype Chain.const jj = { kk: 1 }; // delete the property kk delete jj.kk; console.assert(Object.hasOwn(jj, "kk") === false); delete obj.key-
similar to
delete obj[key]. 〔see Property Dot Notation vs Bracket Notation〕
Edge cases
On non-object
// warning. Using delete on non-object return true console.assert((delete 3) === true);
On non-exist property
// warning. Using delete on non-exist property return true const jj = {}; console.assert((delete jj.k) === true);
On frozen object
// example of failure due to frozen object const jj = { pp: 1 }; Object.freeze(jj); try { delete jj.pp; } catch (xerr) { console.log("delete property pp failed.\n", xerr); }
On array, result sparse array
// using delete operator results a sparse array const xx = [0, 1, 2, 3]; delete xx[0]; console.assert(Object.hasOwn(xx, "0") === false);
🟢 TIP: Never Use the Delete Operator
- Do not use the delete operator to delete array element. That results a Sparse Array . Use Array.prototype.splice to delete elements in array. Best is actually set items to null.
- 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.