How does javascript by reference work?

I am relatively new to Javascript and am working on a large project currently written exclusively in js. One of the concepts I read is

Passing an object through an object.

The following code seems to ignore the rule that js passes the link in case of objects.

var a = {b:2};
var modify = function(a) {a = {d:4}};
modify(a);
print a; //a is still {b:2}.

Why has the value of a in the above example not changed?

Note. The http://snook.ca/archives/javascript/javascript_pass states that objects are passed by reference in Javascript.

+4
source share
3 answers

Passing an object, passing it by reference.

. JavaScript pass-by-value. , . , , .

, , , .

:

var a = {b:2};
var modify = function(a) { 
  delete a.b;
  a.d = 4;
};
modify(a);
print a;

tl; dr: a, b.

+7

JavaScript , , swap:

var a = 3;
var b = 5;
swap(a, b);
// Implement swap so that a is now 5 and b is now 3
// It is impossible.
+7

, , , .

0

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


All Articles