8

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 6

10

you can assign a new array to it:

var array = ["element1","element2","element3"];
...
array = new Array();

OR

array = [];
Sign up to request clarification or add additional context in comments.

1 Comment

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.
6

Assign an empty array to it

   x = []

Comments

4
array.length = 0

should work.

Comments

3

What about delete?

delete array

Or to delete a single index:

delete array[x]

1 Comment

@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)
1
var array = ["elem", "item"];
...
array = []; // Empty!

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.