Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference a Javascript variable by a text alias

Tags:

javascript

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".

like image 309
Johann Avatar asked Jan 28 '14 07:01

Johann


People also ask

Are JavaScript variables by reference?

Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.

What is reference type variable in JavaScript?

Whenever you create a variable in JavaScript, that variable can store one of two types of data, a primitive value or a reference value. If the value is a number , string , boolean , undefined , null , or symbol , it's a primitive value. If it's anything else (i.e. typeof object ), it's a reference value.


1 Answers

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]
like image 103
Sarath Avatar answered Oct 25 '22 23:10

Sarath