eval (JavaScript)

Evaluates an expression or statements.

Defined in

Top-level functions (JavaScript)

Syntax

eval(string)
Parameter Description
string An expression, or one or more statements optionally ending in an expression. The string can include the names of existing objects, properties, and variables.

Usage

This function executes the statements, if any, then returns the value of the expression, if any.

You do not have to use eval to evaluate an embedded arithmetic expression; this happens automatically. However, you might save an arithmetic expression as a string and use eval to obtain its value later.

Examples

This example creates a string variable containing an arithmetic expression, then later evaluates the expression.
function p(stuff) {
	print("<<<" + stuff + ">>>");
}

var e = "x + y";
var x = 1;
var y = 2;
var z = eval(e);
p(z); // 3

This example creates a string variable containing two statements, then later evaluates (executes) the statements.

function p(stuff) {
	print("<<<" + stuff + ">>>");
}

var e = "var x=1, y=2; z = x + y";
eval(e);
p(z); // 3

This example creates a string variable containing a statement and an expression, then later evaluates them.

function p(stuff) {
	print("<<<" + stuff + ">>>");
}

var e = "var x=1, y=2; x + y";
z = eval(e);
p(z); // 3