JavaScript Eval Alternatives
Douglas Crockford, in his book "JavaScript: The Good Parts," famously wrote: "eval is Evil." Experts agree: JavaScript's eval function introduces security issues, dramatically slows script execution and makes code much more difficult to read and maintain. Thankfully, an informed programmer can nearly always avoid using the eval method by taking advantage of the many available alternatives. Though widely scorned, the "eval()" function does play an essential role in JavaScript programming: it causes a web browser to immediately execute code passed to it as an argument.
-
Code Execution
-
Beginning programmers often mistakenly believe they must call the eval operator on other functions to ensure that a web browser executes code. This is a mistake: Web browsers automatically execute any accessible JavaScript function. An example of this mistaken code might look like:
'eval("function m() {alert 'function executed' }");'
However, it would execute more efficiently if it were written:
'function m() {alert 'function executed' }");'
Dynamic Property Access
-
JavaScript programmers trained in other languages may use the "eval()" function to access a dynamically added property. But JavaScript offers programmers a vastly superior alternative called "dynamic properties." Dynamic properties allow a program to access any code so long as it is known at the time of writing. Programmers access these properties using square brackets rather than dot notation, like so:
'object[sampleProperty]'
-
Functions
-
A programmer may sometimes access a function using the eval method, especially after using a dynamically created string to create a function during code execution. A programmer might use this technique like so:
'var dynamicFunction = 'alert("This function created on the fly!")';'
'eval(dynamicFunction);'
But an experienced programmer could avoid calling "eval()" with only a single line of extra code by placing the dynamically created function in a variable and calling a function from the variable:
'var dynamicFunction = 'alert("This function created on the fly!")';'
var functionVariable = new Function(dynamicFunction);
functionVariable();'
Code Libraries
-
Programmers can avoid using "eval()" by relying upon alternatives provided by JavaScript libraries. Libraries such as MooTools, jQuery and Dojo provide programmers with functions and code patterns that avoid the "eval()" function wherever possible. A programmer that relies on these libraries will effortlessly take advantage of alternatives to the "eval()" function. This alternative to "eval()" also provides programmers with a host of other tools for JavaScript programming.
-
References
- "JavaScript: The Good Parts"; Douglas Crockford; 2008
- "JavaScript: The Definitive Guide"; David Flanagan; 2011
- "JavaScript Patterns"; Stoyan Stefanov; 2010
- 24Ways; Don't Be Eval(); Simon Wilson
- Go 4 Expert; Workarounds for JavaScript "eval"; Pradeep; Sept. 2008