3.7. Evaluating eval()

In a compiled language like C# and Visual Basic, it is difficult to create and use code dynamically. The .NET Framework provides the CodeDOM (code document object model) classes for defining functionality and then producing the equivalent code, but this is not typically employed during code execution, because of its difficulty. JavaScript is dynamic in that it allows types to be created and modified on the fly. Furthermore, it natively supports the ability in the eval() function to have any arbitrary script executed. It functions just as if it were a predefined piece of code. This means that you can easily write code that uses runtime values during code execution to create new code that is then executed. Essentially, you can create and execute code on the fly based on other input and variables.

Variable assignments can be based on any runtime condition and used elsewhere in JavaScript code. Listing 3-23 assigns some names to variables and then creates a string which is a piece of code that aggregates the values into a single variable and then displays that variable. Note that the values are pulled together into a piece of code that will use them all. This is distinctly different from having a piece of code that combines strings. The variables happen to be strings, but the eval statement is simply executing a piece of code passed to it as a string.

Example 3-23. Using eval()
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Using eval</title> <script ...

Get Professional ASP.NET 3.5 AJAX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.