Alternative to eval() javascript [duplicate]

Javascript is a very flexible language in this regard. There are very very few cases where eval() is the right answer to any given question, and it certainly isn’t necessary here.

If your a and b variables are part of an object, you can access them with string subscripts:

ie myobj.a could also be referenced as myobj['a'].

From that, you can use a variable for the subscript, and thus you can reference any element in myobj dynamically — ie:

var myobj = {a : 5, b : 10};

var dynamicProperty1 = 'a';
var dynamicProperty2 = 'b';

//gives 15.
alert( myobj[dynamicProperty1] + myobj[dynamicProperty2] );

No eval() required. You can build the dynamicProperty strings however you wish, so there’s virtually infinite flexibility.

If your a and b variables are globals, JS globals in the browser are actually children of the window object, so you can still use this technique even with globals.

ie your global variable a could also be accessed via window.a or window['a'], with the latter option allowing you to do the same dynamicProperty trick described above.

Hope that helps.

Leave a Comment