0

I'm currently reading "Datastructures and Algorithm with JavaScript" by Michael McMillan. On page 39 he implements a clear function for a list, i.e. the function clears out the element of a list.

function clear() {
  delete this.dataStore;
  this.dataStore = [];
  this.listSize = this.pos = 0;
}

Wouldn't assign this.dataStore with undefined or null achieve the same result? Or why not immediately assign an empty array to this.dataStore?

I've read that delete removes a property from an object and if no more references to the same property are held, it is eventually automatically released.

As you can see above, he deletes it and then re-creates it. So, does the delete operator make sense if he doesn't want to release the property anyway? Wouldn't simply re-assigning this.dataStore with an empty array [] be more efficient and equally effective?

thadeuszlay
  • 2,787
  • 7
  • 32
  • 67
  • 1
    It's not *exactly* the same in all cases, but it will be the same in most. Very strange to do, you're right, it seems pointless - easier to just assign a new array immediately – CertainPerformance Oct 28 '19 at 22:57
  • It's possible that the author was working from some assumption that doing that would accelerate garbage collection, but in almost all cases it's a really bad idea to do stuff like that. – Pointy Oct 28 '19 at 22:58

1 Answers1

0

Does the delete operator make sense if he doesn't want to release the property anyway?

No! It's probably caused by the same old misconception about what delete does.

Wouldn't simply re-assigning this.dataStore = [] be more efficient and equally effective?

Yes, it would have the same effect[1], and be much more efficient.

1: assuming the property doesn't have a getter/setter or is non-enumerable.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375