Core function |
Syntax
eval(string)
Parameters
string | A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. |
Description
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 JavaScript statements, eval
performs the statements. Do not call eval
to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.
If you construct an arithmetic expression as a string, you can use eval
to evaluate it at a later time. For example, suppose you have a variable x
. You can postpone evaluation of an expression involving x
by assigning the string value of the expression, say "3 * x + 2"
, to a variable, and then calling eval
at a later point in your script.
eval
is also a method of all objects. This method is described for the Object
class.
Examples
Example 1. Both of the print statements below display 42. The first evaluates the string "x + y + 1"
; the second evaluates the string "42"
.
var x = 2
Example 2. The following example uses
var y = 39
var z = "42"
print(eval("x + y + 1"))
print(eval(z))eval
to evaluate the string str
. This string consists of JavaScript statements that assigns z
a value of 42 if x
is five, and assigns 0 to z
otherwise. When the second statement is executed, eval
will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z
.
var str = "if (x == 5) {print('z is 42'); z = 42;} else z = 0; "
Example 3. The following example creates
print("z is ", eval(str))breed
as a property of the object myDog
, and also as a variable. The first print statement uses eval('breed')
without specifying an object; the string "breed"
is evaluated without regard to any object, and the print
statement displays "Shepherd"
, which is the value of the breed
variable. The second print statement uses myDog.eval('breed')
which specifies the object myDog
; the string "breed"
is evaluated with regard to the myDog
object, and the print
statement displays "Lab"
, which is the value of the breed
property of the myDog
object.
function Dog(name,breed,color) {
this.name=name
this.breed=breed
this.color=color
}
myDog = new Dog("Gabby")
myDog.breed="Lab"
var breed='Shepherd'
print("eval('breed'))
print("myDog.eval('breed')) See also
Object.eval
method
Last Updated: 10/31/97 16:38:00