Are there any rules of thumb when JavaScript values ​​are copied by reference rather than by value?

Even as a somewhat experienced JS dev, I find myself constantly amazed at shallow and deep copies of objects.

Are there any rules of thumb when JavaScript values ​​are copied by reference rather than by value for the main types of objects? For example, I know that string values ​​are always copied by a value of not reference.

+6
source share
2 answers

In JavaScript, all objects are stored and transmitted "by reference."

var a = { v: 'a' }, b = { v: 'b' }; a=b; bv='c'; 

a and b will refer to the same object; av == 'c' and bv == 'c' .

Primitive data types ( string , number , boolean , null and undefined ) are immutable; they are passed by value.

 var a = 'a', b = 'b'; a=b; b='c'; 

Since we are dealing with primitives, a == 'b' and b == 'c' .


Pedants will tell you that JavaScript is not a cross-reference in the classic sense, or that it is a “clean password”, but I think it complicates things for practical purposes. No, you cannot directly change the argument passed to the function as if it were a variable (which would be true if the language was true pass-by-reference), but you also do not get a copy of the passed object as an argument (as if it were was true pass-by-value). For most purposes (from the point of view of the user of the language, you), the objects passed to the function are references, since you can modify this object and influence the object of the caller. See also fantastic answers to this question .

+4
source

OK, let me explain your code:

 var x, y; x = { 'blah': 'foo' }; y = x; x = { 'bar': 'bas' }; 

So, you declare two variables, and then assign the value of the object to the first variable:

 x = { 'blah': 'foo' }; 

So what is going on here:

  • The object literal - { ... } - is evaluated, which leads to the creation and initialization of a new own object.
  • A reference to this object is assigned to the variable x .

Next this line

 y = x; 

just copies the link that is stored in x , the variable y . Now both variables keep the same reference to the object.

Finally this line

 x = { 'bar': 'bas' }; 

assigns a new value to the variable x . The object literal is evaluated, which leads to the creation / initialization of another object, and the reference to this object is stored in x .

However, the y variable still contains a reference to the first object.

+2
source

Source: https://habr.com/ru/post/907255/


All Articles