DEV Community 👩‍💻👨‍💻

Barrios Freddy
Barrios Freddy

Posted on

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 on

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.

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.