Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding pass by reference vs value with functions

Tags:

javascript

As I understand objects are passed by reference in JavaScript (and primitives are passed by value?).

var a, b;
a = {
    Foo: "Bar"
}
b = a;
a.Foo = "Other";
console.log(b.Foo); // "Other"

This worked similarly with arrays but did not work like I expect with functions:

var a, b;
a = function(){ return 20; }
b = a;
a = function(){ return 40; }
console.log(b()); // returns 20 ?

I'm confused because I thought functions are objects. Shouldn't the above example return 40?

like image 414
Stereo99 Avatar asked May 12 '14 12:05

Stereo99


People also ask

What is the difference between pass by value and pass by reference in functions?

Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself). Pass by value means the called functions' parameter will be a copy of the callers' passed argument.

What is difference between call by value and call by reference for functions?

While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”. While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References.

How can you pass value by reference in function?

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.


1 Answers

In the first case, a.Foo = ..., You are changing the value of a property in the object, referred by both a and b. This is called mutating an object.

But in the second case, you are making a refer a new function object. Now, a and b are referring to different function objects.

That is why you are getting 20 in the second case.

like image 71
thefourtheye Avatar answered Oct 07 '22 19:10

thefourtheye