DEV Community

Barrios Freddy
Barrios Freddy

Posted on

3 3

How to empty an array in JavaScript

The simple way to empty an array in JavaScript is through assigning 0 to the property length of the array affected. For Example

let numbers = [1,3,5,7,9];

numbers.length = 0;

console.log(numbers);
// []

Enter fullscreen mode Exit fullscreen mode

This is possible because the length property is read/write property in an array. Therefore, you can assign zero and the array will be clear.

Top comments (4)

Collapse
 
bttodd11 profile image
Brian Todd โ€ข

Wouldnt it be the same assigning to an empty array?
let numbers = [] ;

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ โ€ข โ€ข Edited

Nope. If you had another reference to the original array, the original array would still remain at the other reference - you have done nothing to the original array.

Compare:

let numbers = [1, 3, 5, 7, 9];
let numbers_b = numbers; // another reference to same array
numbers.length = 0;

console.log(numbers_b);
// []
Enter fullscreen mode Exit fullscreen mode

And:

let numbers = [1, 3, 5, 7, 9];
let numbers_b = numbers; // another reference to same array
numbers = [];

console.log(numbers_b);
// [1, 3, 5, 7, 9]
Enter fullscreen mode Exit fullscreen mode

Assigning to an empty array does exactly that - assigns a new array to the variable. Entirely different to emptying an existing array. 'Emptying' an array by simply overwriting it with a new empty array could easily cause unexpected problems.

Collapse
 
jackydev profile image
JacKyDev โ€ข

I think Not..
Its the Same result but the author used the existing Array in context and you create an complete new Array for context

Collapse
 
bias profile image
Tobias Nickel โ€ข

yes, any just by doing so, the author introduce a implicit dependencies between components. Using the same array all over the and somewhere it get emptied will cause some nice side effects.

This will give you some fun debugging session.