Can we pass variables by reference in JavaScript?

Les variables sont passées par valeur, les objets par référence. Les tableaux en JavaScript sont des objets.

We will check each case ...

Case of a simple variable

The test() function adds a string to a string given as a parameter.

function test(z)
{
   z = z + "suffix";
}

var x = "demo";
test(x);
document.write(x);

One can verify that the variable x is not modified outside the context of the function.

The same would be true with a number.

Case of a String object

var x = new String("demo");
test(x);
document.write(x);

Simple objects like String, Boolean, Number, are passed by value.

Case of an Array object

The testa() function adds an element to an array given as parameter.

function testa(a)
{
   a.push("lastitem");
}

x = new Array("one", "two", "three");
testa(x);
document.write(x);

We see that an Array is passed by reference, since the element "lastitem" added in the function body is included in the array after the function call.

Is this true also for an array declared as a literal?

var y = [1, 2, 3];
testa(y);
document.write(y);

The answer is yes.

In conclusion, if we want to pass a simple variable by reference, it must be included in an array ... The code will be amended as follows:

x = "demo";
x = [x];
testa(x);
x = x.join('');
document.write(x);

The join() function converts the array to a string after the function call. This increased the code but due to lack of dereferencing operator in JavaScript, it remains the easiest way to pass a string by reference.

Complete example to pass a string by reference

function testb(a)
{
  var x = a[0];	
  x += "suffix";
  a[0] = x;
} 

x = "demo";
x = [x];
testb(x);
x = x[0];
document.write(x);

The string, although modified in the function, beeing part of an array is changed in the global scope. It is more complicated, but it is possible.

Assignment inside a function

The assignment in a function, either for an object or an array has no effect outside the scope of the function. This is why giving an object as argument is sometimes called "call-sharing" rather than "call by reference".

var ta = [ "a", "b", "c"]
function testb(x) {
   x = ["zero"]
}
testb(ta)
document.write(ta)

Result

So if we want to initialize an array or object in a function, we must delete its contents rather than assign it with [] or {}.

© 2012-2016 Xul.fr