eval() — execute JavaScript code from a string





A string that contains the JavaScript expression to be evaluated or the statements to be executed.


The value of the evaluated code, if any.


eval() throws a SyntaxError if code is not legal JavaScript code. If the evaluation of code raises an error, eval() propagates that error.


eval() is a global method that evaluates a string of JavaScript code. If code contains an expression, eval evaluates the expression and returns its value. (Some expressions, such as object and function literals look like statements and must be enclosed in parentheses when passed to eval() in order to resolve the ambiguity.) If code contains a JavaScript statement or statements, eval() executes those statements and returns the value, if any, returned by the last statement. If code does not return any value, eval() returns undefined. Finally, if code throws an exception, eval() passes that exception on to the caller.

eval() behaves different in ECMAScript 3 and ECMAScript 5, and in ECMAScript 5, it behaves differently in strict mode and non-strict mode, and a minor digression is necessary in order to explain these differences. It is much easier to implement efficient interpreters when a programming language defines eval as an operator instead of as a function. JavaScript’s eval is a function, but for the sake of efficiency, the language draws a distinction between direct, operator-like calls to eval() and ...

Get JavaScript: The Definitive Guide, 6th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.