Sunday 6 March 2016

Assigning objects in Javascript: shallow or deep copy?




I want to know if javascript does shallow or deep copy when copying objects.




const a = ['value1', 'value2'];
const b = ['value3', 'value4'];
const new_ab = [a, b];


new_ab are going to have new allocated values or a reference? If it is a deep copy, how can I make it to be swallow? Thanks.


Answer



As alluded in the comments, JavaScript operates entirely on references, the only exception being that primitive values are kept on the stack and a program does not therefore require a reference to access them. In your example all variable declarations create new values - each an instance of Array - however what is returned from declaring an array is a reference, not the array itself. For example, [1, 2] is an array of values (integers), but [a, b] is an array of references.




So... nothing is copied. We can demonstrate this by placing an object as an element of an array and inspecting that a previously assigned property is still accessible through the new 'parent' array.



(And to answer your question in the comments, yes, your example is more performant than if you (or JavaScript) were to copy values.)





'use strict';

const arrayOne = [];


arrayOne.someProperty = "This string is a property of `arrayOne`, " +
"accessed via the reference to it in `arrayTwo`."

const arrayTwo = [arrayOne];

span.innerHTML = arrayTwo[0].someProperty;






No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...