Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does javascript pass by reference work?

Tags:

javascript

I am relatively new to Javascript and working on a big project currently written exclusively on js. One of the concept I have read is

Passing in an object, passes it in by reference.

Following code seem to defy the rule that js passes reference 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 hasn't changed?

Note: It is mentioned in http://snook.ca/archives/javascript/javascript_pass that objects are passed by reference in Javascript.

like image 901
raju Avatar asked Dec 08 '22 08:12

raju


1 Answers

Passing in an object, passes it in by reference.

No. JavaScript is always pass-by-value. If you pass an object, then the value is a reference to the object. If it was pass-by-reference, you would get a reference to the variable that is passed into the function.

You can mutate the object itself by adding, removing or changing properties, but changing the value of the parameter doesn't magically change the value of the passed variable.

Example:

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

tl;dr: You can never change the value of a variable a by assigning a different value to a variable b.

like image 125
Felix Kling Avatar answered Dec 21 '22 19:12

Felix Kling