DEV Community

Discussion on: How to empty an array in JavaScript

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.