Pass a string by reference in Javascript

Strings in Javascript are already passed “by reference” — calling a procedure with a string does not involve copying the string’s contents. There are two issues at hand:

  • Strings are immutable. In contrast to C++ strings, once a JavaScript string has been created it cannot be modified.
  • In JavaScript, variables are not statically assigned slots like in C++. In your code, metric is a label which applies to two entirely separate string variables.

Here’s one way to achieve what you want, using closures to implement dynamic scoping of metric:

function Report(a, b) {
    this.ShowMe = function() { alert(a() + " of " + b); }
}

var metric = "count";
var metric_fnc = function() { return metric; }
var a = new Report(metric_fnc, "a"); 
var b = new Report(metric_fnc, "b"); 
a.ShowMe();  // outputs:  "count of a";
metric = "avg";
b.ShowMe();  // outputs:  "avg of b";

Leave a Comment