For example, given A = [1, 2, 3, 4];
, what’s the best way to completely clear it? I was wondering if there’s something like .remove()
for an empty array JavaScript
operation.
Hi,
You can set length to 0. Here is how you can do it:
let A = [1, 2, 3, 4];
A.length = 0;
console.log(A); // []
It’s the quickest and most memory-efficient method. I often use this when resetting large data arrays in dashboards or forms.
You can also reassign to a new array. I use this for local variables or temporary arrays, but if other variables reference the original array, they won’t be cleared.
let A = [1, 2, 3, 4];
A = [];
console.log(A); // []
You can also use splice()
for in-place clearing:
let A = [1, 2, 3, 4];
A.splice(0, A.length);
console.log(A); // []
This saved me in a shared-state app where multiple components referenced the same array. Splice cleared it without breaking bindings.