Strings and the ECMAScript Eval Function
Mastering the ECMAScript (JavaScript) eval Function – Part III
Forward: In this part of the series, we see how a string can be used as argument to the eval function.
By: Chrysanthus Date Published: 26 Jul 2012
Introduction
This is the third last part of the series, Mastering the ECMAScript eval Function. In this part of the series, we see how a string can be used as argument to the eval function.
String Literal in Argument
Can a string literal be used as argument to the eval() function, in the ordinary sense? The answer is No. Execution of the following script stops at the line of the eval function:
<script type="text/ECMAScript">
myVar = eval("one");
alert(myVar);
</script>
If there is an error in a line of code, ECMAScript would stop compilation (or execution) at that line. The first statement of the above code is considered by ECMAScript as erroneous.
String Variable in Argument
A variable, whose value is a string literal cannot be used in the argument of the eval() function in the ordinary sense. The following script does not work because compilation ends at the line of the eval function:
<script type="text/ECMAScript">
strVar = "one"
myVar = eval(strVar);
alert(myVar);
</script>
Expression in Quotes
Let us try something here. Let the argument of the eval() function be a string whose content is a string variable. The following script works without any problem.
<script type="text/ECMAScript">
strVar = "one";
myVar = eval("strVar");
alert(myVar);
</script>
The first line of the script declares a string variable. In the second line, for the argument of the eval() function, it is the variable that is in quotes; it is not the string literal. So, for the eval argument, you have a string whose content is a variable and not a string literal. The eval function returns the value of the variable. The last statement displays the string literal.
Here, we have seen that putting a variable, in quotes, as argument to the eval function does not create an error. And, that is a secret.
The truth is, putting an expression in quotes, as argument to the eval() function, does not cause an error. In fact, when you do this, the eval() function evaluates what is in the quotes and returns whatever has to be returned.
If an expression is in quotes the eval function evaluates the expression. If there is anything to return, it returns it. If there is nothing to return it returns the expression in executable form. That is how the eval function behaves. The expression returned, remains at the position of the eval function. The characters of the expression returned cannot be seen, but they are there and the expression can be accessed by statements below it.
Let us look at examples that are more involving.
Consider the following expressions:
alert("one");
alert("two");
alert("three");
Assume that these are three consecutive statements in a script. When the script is run, the first alert statement will display “one”; the second will display “two” and the third will display “three”.
In order for you to have these three statements (or multiple statements) as argument of the eval() function, you have to respect the following rules:
- Enclose the three statements in quotes.
- Escape all the special characters.
- Have semi-colons between statements and have them escaped.
The following line illustrates this:
eval("alert(\"one\"); alert(\"two\"); alert(\"three\")");
The following code runs without any problem:
<script type="text/ECMAScript">
eval("alert(\"one\"); alert(\"two\"); alert(\"three\")");
</script>
The three alert statements display their values; you can try the code
In this section I will show you a special case of the use of the eval() function. I will not give detail explanation of the use of the eval() function here.
A JSON file is a text file whose content is an ECMAScript object literal. The content begins with the open curly brace {, and ends with the close curly brace, }. Here is a simple example of a JSON file (all the content):
{
property1:"an item",
myArray = ["item one", "item two", "item three"],
myFn:new Function ("x","y", "var z = x + y; return z*z;")
}
All what you write inside the curly braces should be in accordance with the syntax for the content of an object literal.
Ajax and JSON File
To download a JSON file by Ajax, what you have to do is to put the name of the file at the end of the URL of the in the Ajax object open() method. Something like this:
myAjax.open("GET", "http://www.mywebsite.com/xxx.json", true);
where xxx.json is the name of the file. Note that the file has the extension, json.
After a successful download, the Ajax object property that would hold the content of the file is, responseText.
Once you have your URL as shown above, the content of the file will be the value of the responseText property of the Ajax object. So, if the name of your Ajax object were, myAjax, then to access the value of the file responseText property, you would type:
myAjax.responseText
Note the dot in between, myAjax and responseText. The aim is to have the content of the JSON file as a usable ECMAScript object. The value of the responseText is not a usable (executable) ECMAScript object; it is a string.
There are two steps to make it an ECMAScript object. First you have to enclose the expression, myAjax.responseText in brackets and as a string. Next, you use the top level ECMAScript eval() function to convert it into an ECMAScript executable code (object literal). To achieve this enclosure, you do something like this:
myString = "(" + myAjax.responseText + ")";
This gives you the string, "(myAjax.responseText)". If we now pass this string as argument into the eval() function as shown below, we would have a usable (executable) ECMAScript object (this is the second step):
eval(myString);
The eval() returns an executable ECMAScript object literal. It is normal practice, to assign the object literal in the browser page, to a global variable. So it is normal to have a statement like:
myGVar = eval(myString);
This global variable, which is now an object can be access from anywhere in the script.
This is effectively what you would have:
myGVar = {
property1:"an item",
myArray = ["item one", "item two", "item three"],
myFn:new Function ("x","y", "var z = x + y; return z*z;")
}
If you want the value of the object property, property1, you would type:
myGVar.property1;
If you want the object array value at index 1, you would type:
myGVar.myArray[1];
If you want to execute the method inside the object, you would type something like,
myGVar.myFn(2,3);
where 2, 3 are arguments for the myFn method (function).
I will not do any more explanation than what I have done so far concerning the eval() function and the JSON file.
This is what the ECMAScript specification says about the eval function:
The argument of the eval function is a string. If the string represents an expression, eval evaluates the expression. If the argument represents one or more ECMAScript statements, eval performs the statements. Do not call eval to evaluate an arithmetic expression; ECMAScript evaluates arithmetic expressions automatically.
If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. If the argument of eval is not a string, eval returns the argument unchanged.
Let us look at the sentences. The first sentence is “The argument of the eval function is a string.” Now we have done so many things with the eval() function without using the string as an independent variable. (eval and eval() are the same thing in this series). In fact, we have not succeeded to use string as an independent argument: We have considered literals; string has not worked as literal. We have considered variables, whose values are string literals; this has not worked. Such variables do not function inside the argument. Let us just be patient and we shall see what this first sentence really mean in the next part of the series.
The second sentence “If the string represents an expression, eval evaluates the expression”. This sentence is related to the first; it is giving more clues to what the first is.
The third sentence is, “If the argument represents one or more ECMAScript statements, eval performs the statements.” Well, if the multiple statements are typed in the ordinary way as we saw above, then they will not work. We have seen the condition under which these statements work above.
The fourth sentence is “Do not call eval to evaluate an arithmetic expression; ECMAScript evaluates arithmetic expressions automatically.” We have to interpret this sentence, since we have successfully used eval to evaluate arithmetic expressions. The normal way to evaluate arithmetic expressions is to assign numbers to variables, and then put the variables in an arithmetic expression. You do not need an eval function to evaluate an arithmetic expression. So when should use the eval function for arithmetic expressions only if it brings out some advantage.
The fifth sentence, adds more meaning to the previous sentence.
The sixth sentence is “If the argument of eval is not a string, eval returns the argument unchanged.” We have to be careful here. We have seen statements that are correct in themselves but cause an error when they form the eval argument. We have seen other statements that are correct in themselves and eval has converted them into executable code.
Any single statement without an independent string or a variable that holds an independent string literal and without the terminating semi-colon works as argument to the eval() function. If a single expression is put in quotes, it would work as argument to the eval() function, on condition that its special characters are escaped. This expression in quotes can have variables holding independent string literals. If you want multiple statements to be the argument of the eval() function follow the rules below:
- Enclose the statements in quotes.
- Escape all the special characters.
- Have semi-colons between statements and have them escaped.
Using the eval() function with the JSON file is a special case, which I have given above.
That is it. I hope from now on you will use the eval() function with more confidence.
Chrys
Related Links
Major in Website DesignWeb Development Course
HTML Course
CSS Course
ECMAScript Course