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);
// []
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)
Wouldnt it be the same assigning to an empty array?
let numbers = [] ;
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:
And:
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.
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
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.