8

How do i unset an array in javascript? i just want to empty it - so it has nothing in it keys or anything

Richard Peers
  • 1,131
  • 3
  • 9
  • 7

6 Answers6

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
6

Assign an empty array to it

   x = []
user187291
  • 53,363
  • 19
  • 95
  • 127
4
array.length = 0

should work.

pms1969
  • 3,354
  • 1
  • 25
  • 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
1
var array = ["elem", "item"];
...
array = []; // Empty!
Björn
  • 29,019
  • 9
  • 65
  • 81
0

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
Manatax
  • 4,083
  • 5
  • 30
  • 40