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
".
Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With