2

When removing a property from an object, I've used the delete operator in the past. But when I had my code reviewed by a person with a CS background, they wanted me to find another way of removing the property because it was an "expensive" task (not sure what that means). Since I'm self taught I wanted to ask if deleting in Js is something I should consider using as last resort? I've looked at other responses within SO like this but couldn't find anything that makes reference to this.

Mix Master Mike
  • 1,079
  • 17
  • 26
  • If you find yourself wanting to delete properties, you probably want to use a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). Another possibility is that you might want to explore another approach entirely to the problem you're trying to solve, one that is expressed more naturally in JavaScript. – Patrick Roberts Oct 28 '20 at 21:24
  • 1
    Expensive means it requires more computing processes and takes a longer time to execute the code. I don't know if it's true or not, but even if it's expensive, I'm sure our machines can easily delete some keys.. – Bulent Oct 28 '20 at 21:26
  • @BülentAkgül thanks for that tidbit of information – Mix Master Mike Oct 28 '20 at 21:27

2 Answers2

4

No, it's not considered bad practice. It just depends on what you want to do,

Read this thread: Garbage Collection and JavaScript "delete": Is this overkill/obfuscation, or a good practice?

Fritiof Rusck
  • 404
  • 1
  • 3
  • 11
2

The book "JavaScript, the Good Parts" by Douglas CrockFord says...

The delete operator can be used to remove a property from an object. It will remove a property from the object if it has one. It will not touch any of the objects in the proto- type linkage.

I think you can use the Delete operator without worries. There are many other ways to remove a property from an object, but all they are more expensive in my opinion.

Pablo Darde
  • 5,844
  • 10
  • 37
  • 55