myGlobal.eval( str ) in ECMAScript 262

Evaluate the supplied string as ECMAScript code.


str String The string to evaluate.
Return Type


This global function takes arbitrary code in a single string and evaluates it as ECMAScript code. The evaluated code has the same context as the call to the eval() function.

var person = { name:'Billy' , age:13 };
var objAsString = "{ name:'Billy' , age:13 }";
eval("var anotherPerson = "+objAsString);
// ** person and anotherPerson are identical (but separate) objects

Note: This is one of the most abused functions, and is hardly ever appropriate. The above sample simulates one case where it is useful: using ECMAScript object notation (also called JavaScript Object Notation) to pass data between contexts, and then using eval() to turn the string into a full-fledged object.

Another case where eval() is appropriate is when a user's input will be used for code, such as a mathematical expression like "17*x-8".

It is not appropriate (or necessary) to use eval() to build variable names on the fly. To look up a global variable or function by name, for example, use a reference to the Global object (which is 'window' in web browsers) and look up the variable as a property of that object using the square bracket notation. For example:

var p1 = "something";
var i=1;
var theValue = window['p'+i];
// ** the above assumes an object named 'window' which refers to the Global object,
// ** which is true in web browsers but which is not part of the ECMAScript specification