7

Working example with global var:

var example_var = 'global var example';

var x = function(){
    var var_name = 'example_var';
    alert('Global var value is: ' + window[var_name]);
}

How can I do same thing with a local variable? Like this (not working example):

var x = function(){
    var example_var = 'Local var example';
    var var_name = 'example_var';
    alert('Local var value is: ' + window[var_name]);
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
klesh
  • 75
  • 1
  • 3

4 Answers4

7

If you have no other way, you can try eval it

var x = function(){
    var example_var = 'Local var example';
    var var_name = 'example_var';
    alert('Local var value is: ' + eval(var_name));
}
YOU
  • 120,166
  • 34
  • 186
  • 219
  • This, `eval`, [collecting local variables with a `with` statement and a `Proxy` scope](https://stackoverflow.com/a/41704827/4510033), and [analyzing the function body](https://stackoverflow.com/a/25473571/4510033), would be more or less the only solutions. – Константин Ван Apr 30 '22 at 20:23
3

You don't want to use eval; a locally scoped object might be your best option:

var x = function(){
    var self = {};
    self.example_var = 'Local var example';

    var var_name = 'example_var';

    alert('Local var value is: ' + self[var_name]);
}
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
-3

possibly:

var x = function(){
    var example_var = 'Local var example';
    var var_name = example_var;
    alert('Local var value is: ' + var_name);
}

or:

  var x = function(){
        var example_var = 'Local var example';
       window.var_name = example_var;
        alert('Local var value is: ' + window[var_name]);
    }

or

  var x = function(){
            var var_name = 'Local var example';    
            alert('Local var value is: ' + var_name);
        }
matpol
  • 3,042
  • 1
  • 15
  • 18
  • Question is about to access variable by name. Your examples: 1) var_name value is "example_var" not the value of the example_var 2) Still var_name contain the name of the varible not it's value 3) there is no other variable you try to access. – Péter Aug 13 '13 at 10:37
-4

At the moment there are two solutions to this problem.
1. eval(), but i really don't like to use evil()
2. we can change variable declaration from var to this:

var x = function(){
    this.example_var = 'this.var example';
    this.var_name = 'example_var';
    alert('Local variable value is: ' + this[var_name]);
}
klesh
  • 75
  • 1
  • 3