Many JavaScript programmers have come across the EVAL command, as it has been around since JavaScript 1.0 and ECMA-262, but few will have used it. In this article, I’ll take a quick look at several potential uses for this command, including one allowing us to write code that is easier to read, maintain, and has less lines while achieving the same effect. I will also look at how EVAL can assist you when you are using dynamic content in your Web-based applications.

The command syntax for the EVAL command is:
EVAL(“<some JavaScript string>”);

What does EVAL do
The command executes the JavaScript contained within the brackets, in some cases this may return a value which can be assigned to a variable. But, how does this help JavaScript programmers in their day-to-day work?

As EVAL allows you to dynamically create and execute JavaScript, you can use it to reduce the number of lines of code you need to use; you can also use it to create JavaScript to perform activities that would be significantly more difficult without using the command. In many cases, you can move this functionality out of a single page and convert it into a generic function that you can reuse thanks to the EVAL function.

Reducing the number of lines of code
You can use this command in a variety of activities, for example, if you have a list of fields’ names which must contain a value on an HTML form, conventionally you would have had to write an if/then for each field, leading to verbose code, which is not the easiest to read, maintain, or debug, especially within a large and/or complex Web application (See Listing A). Using the EVAL command, you can reduce this to a simple array and loop as shown in this Listing B.

As you can see, you have reduced the size of the code required to check the eight fields from 32 to 10 with no loss of functionality, but with a savings of about 70 percent in terms the of number of lines required. Utilizing the EVAL command has also produced a much more user friendly, maintainable and concise code than the traditional approach.

The real power of EVAL
The real power of this command is its ability to work with data that is not known at load time—for example, user-entered data. As I have mentioned, EVAL takes any string that you provide and executes it returning a result, if one is applicable. You can use this to execute JavaScript where what you are being asked to execute is not known at load time. For example if we have a calculation script that takes an equation provided by the user and returns a result, you can use EVAL to perform the calculation.

An example of the use of this command can be seen in the auto-generated function shown in Listing C from MacroMedia’s DreamWeaver Editor.

This code sets the location of the object specified by the targ parameter to that of the value attribute of the selObj drop-down; the other parameter simply resets the drop-down if set to true. The reason that EVAL is used here is that it allows the developer to provide the target for the function, which could be a variety of things, for example:

  • targ value – load the selected URL
  • Document – current window
  • Parent – parent document when using Frames/IFrames
  • newwin – A different window identified by newwin
  • parent.mainframe – a sibling Frame/Iframe identified by mainframe
  • Top – The top level item in the current window

As you can see, the range of possible values for this function makes any conventional or hard-coded approach impossible to implement for this functionality.

Doing this without EVAL
Searching the Internet while doing research for this article, I came across a multitude of code samples that used this command. In many cases, there was no other way to implement the functionality that was required, but in some there was an alternative. For example, it is also possible to implement the code in Listing C by using the elements array of the Form object as shown in Listing D.

As both approaches achieve the same end, with about the same amount of code and complexity, which one should you use and why?

From the research that I have been able to do, primarily reviewing content in the comp.lang.javascript newsgroup, I have been able to determine that in some cases there is a performance difference between the two approaches. For most developers, the numbers appear to be insignificant, thus it is a matter of preferred style and coding standard. However, in some cases, EVAL outperforms conventional coding.

The first area is where EVAL can make a significant difference: Numeric Division. Because EVAL executes the entire equation in one go rather than trying to process each part separately, it has a significant edge for these kinds of calculations. A demo proving this is available and the discussion thread concerning it is in the JavaScript newsgroup.

To get a reasonable selection of test data, the tests were run three times using IE 6 (SP1), NN 7.1 and Opera 5, using a new browser instance for each test, all on Windows 98 and the tests were run between 01:00 and 02:00 GMT. The results are listed below in milliseconds in the respective order (IE, NN, Opera).
Table A

 


Using Eval


Split


Split & parseFloat


Split & parseInt

Test Run 1

7580 13190 25040

50370 15700 23510

50970 18290 26640

52670 20270 29930

Test Run 2

7250 16370 33060

52350 16310 25210

54110 22790 28450

50420 22030 32130

Test Run 3

7680 17420 26750

53010 15810 24230

63710 18680 27410

61680 20160 25100

Average

7503 15660 28283

51910 15940 24317

56263 18680 27500

54923 19920 29053

Performance Order

IE, NN, Opera

NN, Opera, IE

NN, Opera, IE

NN, Opera, IE

Test results

Not only do these results show a significant difference between each of the four approaches, but also a significant difference depending on the browser used. Therefore, browser selection, as much as algorithm selection, could play a significant role when you need to perform a large number of calculations on the client machine.

The second area is interaction with the Document Object Model (DOM). The three main approaches here are:

  • Use the EVAL command to create a link directly to the object.
  • Use document.all, which returns all matching objects (IE only).
  • Use getElementByID, which returns the first match it finds.

There is an interesting discussion about this use of EVAL in this type of code in the JavaScript Newsgroup. However, EVAL is not always the best approach; sometimes it can be slower depending on what you are asking it to do.

Just before completing this article, I came across an interesting use of this command to dynamically create and initialize variables that are passed in from the Browsers Query String—or any other similar method—in this thread from 1998. In this example, the developer is taking advantage of the format of the Query String coupled with the JavaScript syntax to allow him to simply run the EVAL command on each name/value pair extracted from the Browsers Query String rather than trying to process them and then assign them to variables within your code.

A word of caution
Despite the advantages of using EVAL, in some cases, the only major problem is the command itself. It will execute whatever is passed to it, so be very wary of using this command in a situation where you don’t trust the users’ honesty or ability completely.

Browser support
As this command has been around since JavaScript 1.0, it is supported in all browsers, so there should be no problems in using it. The only browser-specific issue which you may face will be the result of the code that you pass into the EVAL command itself.

Using the command
This command has powerful potential and is used/misused in a large number of Web sites and books. There appears to be a lot of discussion in the JavaScript community concerning the correct use of this command ranging from the “thou shalt never use EVAL” to “there’s more than one way to do it” camps.

I have not found a technically compelling argument to use EVAL over other methods for general day-to-day development, although there are exceptions as I have discussed in this article. I would like to hear some constructive feedback from all interested parties to this article—help me refine my understanding on the use of this command.