0

How should I pass by reference in a JavaScript function?

For example:

function passByReference(a){
    a = "banana";
}

var x = "apple";
passByReference(x);

Here x should output banana.

I am new to JavaScript; any help would be appreciated. Thanks in advance.

cf-
  • 8,598
  • 9
  • 36
  • 58
azero0
  • 2,220
  • 3
  • 20
  • 31

2 Answers2

2

Wrap the variable with an object. Properties of objects are passed by reference.

function passByReference(a) {
   a.fruit = 'banana';
}

var wrapper = {fruit: 'apple'};
passByReference(wrapper);
Gabriel
  • 862
  • 6
  • 18
  • 1
    Not exactly. Objects are also passed by value. However the properties are references itself. For example: This would not work `a={fruit: 'banana'}` inside the function – Zhonk May 02 '14 at 06:57
  • yeah @zhonk you are right properties are references itself and objects are also passed by value. – azero0 May 02 '14 at 07:33
0

You cannot pass by reference. If you want to modify the state of your caller from within the called function, there are two ways you could do:

Sometimes it fits best to wrap the state in an object:

var x = { valueToChange: 'initialValue' };
passByReference(x);

This works because with objects, a pointer to the address where the object lies is passed. That pointer is passed by value but it still points to the same object.

In some other cases a callback does the trick:

var x = "apple";

passByReference(function (newValue) { x = newValue; });

function passByReference(callback) {
    callback("banana");
}

This works because if you define a function as above it builds a closure together with all variables it references. When your function gets called it really modifies the value of x.

chiccodoro
  • 14,407
  • 19
  • 87
  • 130