11

As stated Here, It seems that the most efficient way to empty an existing array (and NOT to allocate a new one) in javascript is to use:

array.length = 0;

Does the same operation work for plain objects? (aka "associative arrays" or "dictionaries") If not, what is the most efficient way to empty an existing javascript object?

I think that allocating a new one is not the best option, since it will push some extra work to the garbage collector, and will allocate some new memory on the heap, but I might be wrong.

I need a solution that works at least with Chrome and Firefox.

braX
  • 11,506
  • 5
  • 20
  • 33
Sebastien
  • 682
  • 1
  • 14
  • 26

1 Answers1

28

The shortest way to do that is to create a new object. You'd end up garbage collecting all the properties anyway.

var foo = {
    a: 5,
    b: 4
};
foo = {};

You could also iterate over the properties and remove them individually:

for (var prop in foo) {
    if (foo.hasOwnProperty(prop)) {
        delete foo[prop];
    }
}

It's also worth pointing out, as a matter of verbiage, that JavaScript has objects with properties, not associative arrays.

Dennis
  • 32,200
  • 11
  • 64
  • 79
  • 10
    It should be noted that `foo = {}` creates a new object and **leaves the original object as is**. This makes a difference when there are other references to the original object: `var foo = {a:5,b:4}; var bar = foo; foo = {};` At the end, `bar`is still `{a:5,b4}` and **not** `{}` as one might expect. – Ignitor Feb 29 '16 at 13:21
  • 1
    @Ignitor How avoid that and propagate the change to bar too? – Dario Jul 17 '18 at 14:42
  • 1
    @Dario I guess you have to remove the properties individually using `delete` as stated in the answer. – Ignitor Jul 20 '18 at 20:02
  • 1
    Yes i do that with a for that cycle all elements and delete it – Dario Jul 22 '18 at 11:31