5

Is it possible to reference a JavaScript variable by a text alias? For example:

var x = 2;
var y = convertToVariableRef("x");

After calling the above function: "y would be the same reference as x and not just simply copying the value of x into y".

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Johann
  • 27,536
  • 39
  • 165
  • 279
  • there is [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) in JavaScript that evaluates `x` and assign value to `y` – Grijesh Chauhan Jan 28 '14 at 07:41
  • 1
    possible duplicate of [javascript variable reference/alias](http://stackoverflow.com/questions/1686990/javascript-variable-reference-alias) – Ashoka Mondal Jan 28 '14 at 07:49

6 Answers6

4

if you declare an object with out any scope of function its a property of window object, so you can get it reference like this

function convertToVariableRef (ref) {
  return window[ref];
}

var x = 2;
var y = convertToVariableRef("x");

but it just copy the value for primitives , and reference only for non-primitives.

array,objects etc are non-primitives.

var x = [1];
var y = convertToVariableRef("x");
y[0] = 2;

// log: x -->  [2]
Sarath
  • 9,030
  • 11
  • 51
  • 84
3

After calling the above function, y would be the same reference as x and not just simply copying the value of x into y.

No, JavaScript doesn't have references to variables in that sense.

You're better off using an object and a property:

var obj = {x: 2};
var yobj = obj;
consoel.log(yobj.x); // 2

yobj and obj both refer to the same object in memory in the above, and that object has an x property. So modifying x through either reference updates that one object.


Why I said "JavaScript doesn't have references to variables in that sense" above: JavaScript's closures receive an implicit reference to a hidden object, called the variable binding object, that in turn refers to variables. So in that sense, JavaScript has references to variables (indirectly, through a hidden object). But you can't get a reference to that hidden object, so it doesn't really help with what you described.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    In eval does it happens `"y would be the same reference as x "` ? that is the reason I didn't post an answer. – Grijesh Chauhan Jan 28 '14 at 07:43
  • @GrijeshChauhan: Thank you. What I get for answering a question before I'm fully awake. I've corrected it. – T.J. Crowder Jan 28 '14 at 07:46
  • Well, it depends on how you think about it. All variables in JavaScript are references (except for those referring to primitives). – Jakob Jan 28 '14 at 07:48
  • @Jakob: Variables aren't references; variables contain values, and in the case of object references, the value is a reference to an object. But that's quite different from having a reference *to the variable*. – T.J. Crowder Jan 28 '14 at 07:49
  • @T.J.Crowder: Right, better worded like that! I don't think anyone asked for a "reference to the variable" though. The question was how "y would be the same reference as x", which is very much what happens whenever you do `y = x` (as long as the right-hand side is not a primitive). – Jakob Jan 28 '14 at 08:05
  • @Jakob: Pretty sure the OP was looking for a reference to a variable, esp. as the question's example involves a primitive. – T.J. Crowder Jan 28 '14 at 08:06
3

Referencing a primitive variable such as an integer is not possible. If you really want it you could have some listeners watching your value changes by adding some extra complex padding like some frameworks do (such as AngularJS).

But actually, it would be way simpler to wrap your value into an object, which is referentiable, ie:

var x = {value: 2};
var y = x;

Just use x.value or y.value then.

floribon
  • 19,175
  • 5
  • 54
  • 66
3

You could go right on and create an Object reflect and assign properties to it.

var reflect = new Object();
reflect.x = 2;
var y = reflect["x"];

Fiddle: http://jsfiddle.net/wE4Ft/

Re Captcha
  • 3,125
  • 2
  • 22
  • 34
  • 2
    This is by far the simplest and most eloquent approach. It is ideal for situations where you need to reference variables indirectly embedded in html that get extracted by jQuery. – Johann Jan 28 '14 at 08:06
  • 2
    This doesn't work. `var y = reflect["x"];` copies the value, not a reference. See http://jsfiddle.net/wE4Ft/1/ – JustAPoring Jan 29 '14 at 16:32
  • @JustAPoring: You could use this hack: [Fiddle](http://jsfiddle.net/wE4Ft/3/). It's not a good solution, but it depends on your usage. – Re Captcha Jan 31 '14 at 15:26
2

For objects and arrays, two variables can point to the same object or array, but for simple values like numbers or booleans, there is no way in javascript to have two variables pointing to the same primitive value.

You can wrap a primitive value into an object and solve the problem that way.

var x = {val: 2};
var y = x;  // now both y and x point to the same object

x.val = 3;
console.log(x.val);   // 3
console.log(y.val);   // 3 (same value)

And, with property names, you can also use the string name to access the property as in:

var x = {val: 2};
var y = x;  // now both y and x point to the same object

console.log(y["val"]);   // 2   
jfriend00
  • 683,504
  • 96
  • 985
  • 979
2

1) If the value of the variable is a primitive (number, bool, string), you cant get a reference to it. You can only copy it.

2) Even if the variable is NOT a primitive, but is attached to the current scope (i.e., declared with var, like in your example) it's impossible (with two exceptions).

The case that would work is hence a non-primitive, that's part of some other object than the current scope. Like this:

 var obj = { a: [1,2,3], b: 42 };

 var copyOfA = obj.a;

 // do something to copyOfA
 copyOfA.splice(1);

 // now this has changed!
 console.log(obj.a);

The two exceptions are:

  • Using eval (which is not very idiomatic)
  • If the current scope is the global scope (which it most often isn't, since you're not making everything global, RIGHT?)
Jakob
  • 24,154
  • 8
  • 46
  • 57