1

I have some code where I use getters in an array and I've run into an issue where delete isn't deleting the element from the array. I'd like to know if there's a way to get delete working.

Here's some toy code that replicates the issue:

let x = [];
Object.defineProperty(x, 0, {
  get: function() {
    return;
  }
});
delete x[0];

edit: Slicing is actually not an option, it seems, since only the elements themselves and not the getters are copied.

user3747260
  • 465
  • 1
  • 5
  • 14

1 Answers1

4

You need to define the property with the configurable: true option. Then you can delete it and the getter will be removed.

let x = [];
Object.defineProperty(x, 0, {
  configurable: true,
  get: function() {
    return "fake value";
  }
});
console.log(x[0]);
delete x[0];
console.log(x[0]);

See How do I undo a Object.defineProperty call?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • We should make the words "dynamic" and "fake" synonymous... just kidding, but it gave me a good laugh. – StackSlave Nov 06 '20 at 01:40
  • Thanks, this worked. Interesting to note that when defining a getter in an object initializer `configurable` is set to true by default, which would explain why it was working for me elsewhere. Ah javascript. – user3747260 Nov 06 '20 at 01:43