Introduction
One Javascript function that gets used such frequently than it should to be is "eval". "eval" evaluates the content of a text string passed to it and then executes it as if it were normal Javascript code..
Actually, we should never use eval for any purpose in our code, be it dynamic variable access, or dynamic code execute or the likes there is always a workaround. "eval" is usually used by beginners and amateurs most of the times to access some dynamic variable i.e. in a situation where a variable is a part of another varibale name. Example: You have variable str1,str2...strn, so to access them you may write:
Code: JavaScript
var myStr = eval('str'+i); // where i is our counter variable
Solution to Dynamic Variable Access
For those who don't know all global variables are held in the window object, so we can bypass "eval" to access the require variable like this:
Code: JavaScript
var myStr = window['str'+i]; // where i is our counter variable
This much better, faster and safer way to access a dynamic varibale.
Dynamic Code Execution
Sometimes some experienced programmers may still use eval, of course for something quite complicated than accessing a dynamic variable. There also we can avoid using eval, by creating a function with the code to execute and then calling the function. Normally we would do this.
Code: JavaScript
var myCode = 'alert("Howdy?");';
eval(myCode);
Now let's try the non-eval approach,
Code: JavaScript
var myCode = 'alert("Howdy?");';
var myFucn = new Function(myCode);
myFucn();
The alternative method may produce code a bit longer than the eval one, but the later one is better and easier to understand, and it should also run faster.

