Javascript: Get access to local variable or variable in closure by its name [duplicate]

I’m not aware of anything built into JavaScript to reference local variables like that (though there probably should be considering all variables are internally referenced by strings).

I’d suggest keeping all your variables in an object if you really need to access by string:

var variables = {
    "j": 1
};
alert(variables["j"]);

Update: It kind of bugs me that there’s no way to do this like you want. Internally the variable is a mutable binding in the declarative environment records. Properties are bound to the object they’re a property of through the object’s environment records, but there’s actually a way to access them using brackets. Unfortunately, there’s no way to access the declarative environment records the same way.

Leave a Comment