O'Reilly logo

JavaScript: The Good Parts by Douglas Crockford

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

eval

The eval function passes a string to the JavaScript compiler and executes the result. It is the single most misused feature of JavaScript. It is most commonly used by people who have an incomplete understanding of the language. For example, if you know about the dot notation, but are ignorant of the subscript notation, you might write:

eval("myValue = myObject." + myKey + ";");

instead of:

myvalue = myObject[myKey];

The eval form is much harder to read. This form will be significantly slower because it needs to run the compiler just to execute a trivial assignment statement. It also frustrates JSLint (see Appendix C), so the tool's ability to detect problems is significantly reduced.

The eval function also compromises the security of your application because it grants too much authority to the eval'd text. And it compromises the performance of the language as a whole in the same way that the with statement does.

The Function constructor is another form of eval, and should similarly be avoided.

The browser provides setTimeout and setInterval functions that can take string arguments or function arguments. When given string arguments, setTimeout and setInterval act as eval. The string argument form also should be avoided.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required