Modifying javascript arrays

Published on 2024-05-25 by Raul

I've struggled for a couple of days with this bug I had in an Angular application, where changing the source of the grid didn't trigger the watch.

Simplified, my code looked like this

var a = [1,2];
var b = a;
var c = b;

b = [3,4];

 Changing b should also change c. But it didn't. The reason why is that, after all the assignments, a, b and c point to the same memory location.

But when I assign a new array to b, ONLY b points to the new memory location. a and c point to the old one.

So, in order for c to point to the same location, I need to change the EXISTING array, not assign a new array to b.

So, after doing:

b.length = 0; //empty the array
for(var idx = 0; idx < newArray.length; idx++)

 Now ALL 3 variables, a, b and c point to the same location. Angular's watch gets triggered, and everyone is happy :)

Keep in touch


Hey there, I'm Raul, owner of CreativeCLR, a small consulting company.

Feel free to drop me any question you might have on this post using the comment section or the contact page.