Overwrite array in JavaScript

Ivar picture Ivar · Oct 12, 2009 · Viewed 22.9k times · Source

How do I overwrite (or unset and then set) an array? Seems like "array = new_array" doesn't work.

Answer

Guffa picture Guffa · Oct 12, 2009

To create an empty array to assign to the variable, you can use the Array constructor:

array = new Array();

Or you can use an empty array literal:

array = [];

If you have several references to one array so that you have to empty the actual array object rather than replacing the reference to it, you can do like this:

array.splice(0, array.length);