How do i unset an array in javascript? i just want to empty it - so it has nothing in it keys or anything
6 Answers
you can assign a new array to it:
var array = ["element1","element2","element3"];
...
array = new Array();
OR
array = [];
1 Comment
amilaishere
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.
What about delete?
delete array
Or to delete a single index:
delete array[x]
1 Comment
Fabrício Matté
@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 window property or an explicit one it will work in most browsers (delete is implementation-dependent). More info about delete. (but of course, this is not an ideal way to declare arrays)FOR REFERENCE (I know its old and answered)
If you want to empty the array, that has been answered already. If you want to unset the array, you could assign an unset variable...
var undef;
var myArr = [];
...
myArr = undef;
// typeof myArr == undefined