How do i unset an array in javascript? i just want to empty it - so it has nothing in it keys or anything
Asked
Active
Viewed 3.4k times
6 Answers
10
you can assign a new array to it:
var array = ["element1","element2","element3"];
...
array = new Array();
OR
array = [];

marcosbeirigo
- 11,098
- 6
- 39
- 57
-
This code will set the variable "array" to a new empty array. This is perfect if you don't have references to the original array "array" anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. you can use array.length = 0 instead. – amilaishere Sep 25 '15 at 08:34
3
What about delete?
delete array
Or to delete a single index:
delete array[x]

James Brooks
- 1,281
- 5
- 17
- 28
-
2@Tadeck Of course delete doesn't work, delete is for object properties without the `DontDelete` attribute, not `var` or `function` declarations which have the `DontDelete` attribute. If you make the array an [implicit](http://jsfiddle.net/ult_combo/k8nhe/1/) window property or an [explicit](http://jsfiddle.net/ult_combo/k8nhe/2/) one it will work in **most** browsers (`delete` is implementation-dependent). [More info about delete](http://perfectionkills.com/understanding-delete/#property_attributes). (but of course, this is not an ideal way to declare arrays) – Fabrício Matté Aug 10 '12 at 13:03