Sunday, August 01, 2021

Javascript Assignment by Reference

If you have an array variable, say 'a', and you peform an assignment b=a; Javascript does not make a copy of the array. There is just one array in memory. Both 'a' and 'b' are references to the same array. You can change b[0] and that will also change a[0].

If you really want to copy an array, you can execute b=a.splice(0);

However, note that if the elements of the array contain references to other arrays or objects, then those will still be shared between the old array and the new one. Making a complete clone of a complex data structure can be tricky.

One approach is to turn the whole thing into a JSON string using JSON.stringify, and convert it back into a data structure using JSON.parse. This mostly works, but any objects that have methods will lose those methods in the conversion since methods are not encoded in JSON by the JSON.stringify.

The same assignment by reference rules also apply to objects, not just arrays.

Image Credit: Ajay Kumar, CC-BY-SA 2.0

Post a Comment

Note: Only a member of this blog may post a comment.