1. Tech

Your suggestion is on its way!

An email with a link to:

http://javascript.about.com/library/bleval.htm

was emailed to:

Thanks for sharing About.com with others!

Alternatives to "eval"

Join the Discussion

Questions? Comments?

One Javascript command that gets used far more frequently than it ought to be is "eval". This command evaluates the content of a text string and then runs it as Javascript code.

In fact there should never be any need to use eval in your code as there are always more efficient ways to write your Javascript code. Most of the time when Javascript novices use eval it is because they want part of a variable name to be variable. They build the variable name by concatenating the constant and variable parts together like this:

eval('myvar' + num)

Once you realise that all global variables are held in the window array it becomes rather obvious that you can refer to that same field name without needing to use eval by referring to it like this:

window['myvar' + num]

This second way of referencing the same field is as simple to code and way more efficient than using eval.

Where more experienced Javascript programmers may still look at using eval is where they have something more complicated than just a single variable that needs to be evaluated as Javascript. Here the way of avoiding using eval is not quite so obvious until it is pointed out to you that whatever you are trying to evaluate could be treated as a function and so it is just a matter of dynamically creating a function and then running it. So where we might have considered using:

eval(codeToRun)

We now look at coding it as:

var tmpFunc = new Function(codeToRun);
tmpFunc();

This code may be fractionally longer than using eval but it makes it much clearer to someone reading the code as to exactly what it is that the code is trying to do. Browsers should also have a clearer idea of what you want when you code it this way so they should produce faster running code as well.

It is only when the code that you want to "evaluate" itself contains functions that the code required to avoid using eval becomes more complicated.

©2014 About.com. All rights reserved.