See all posts

Empty An Array Without Losing Reference

May 8, 2020
2 min

In JavaScript when you assign an array to a variable, that variable points to the location in memory for that array. This means the variable only has a reference to the array, not the actual value.

In the below example both array1 and array2 point to the same location in memory (same reference). So when we add a new item, the change is visible in both arrays:

let array1 = [1, 2, 3];
let array2 = array1;

array1.push(4);

console.log(array1, array2); // [1, 2, 3, 4] [1, 2, 3, 4]

Let’s say that somewhere in your code, you want to empty the array. Most likely you would do it like this:

let array1 = [1, 2, 3];
let array2 = array1;

array1 = []; // Empty the array (lose reference)

console.log(array1, array2); // [] [1, 2, 3]

Doing it this way, the arrays are no longer returning the same value. So why is array2 not empty? This is because array1 = [] creates a new (empty) array and array1 now points to a different location in memory of the new (empty) array, while array2 still points to the old one.

One way to solve this issue would be to manually assign array2 to point to the new location as well:

let array1 = [1, 2, 3];
let array2 = array1;

array1 = []; // Empty the array (lose reference)
array2 = array1;

console.log(array1, array2); // [] []

But this is solution is quite tedious and error-prone, as we may forget to change all the arrays with the same reference.

A more elegant way to empty an array and not lose the references is to change the length to 0:

let array1 = [1, 2, 3];
let array2 = array1;

array1.length = 0; // Empty the array (keep reference)

console.log(array1, array2); // [] []

Doing it this way we don’t create a new array but modify the existing one, which ensures we don’t lose the reference.

Previous Simple Sitemap For Vue Router Next A Short Cautionary Tale About Refactoring