This translation is incomplete. Please help translate this article from English

Die Methode eval() (engl. to evaluate = evaluieren, ausführen) wertet einen String aus und führt ihn als JavaScript-Code aus.




Ein String, der einen JavaScript-Ausdruck, eine JavaScript-Anweisung oder eine Folge von JavaScript-Anweisungen enthält. Der Ausdruck kann Variablen und Eigenschaften existierender Objekte enthalten.


Einen String, der das Resultat des übergebenen, ausgeführten Quelltext repräsentiert. Wenn das Resultat leer ist, wurde undefined zurückgegeben.


eval() ist eine Funktions-Eigenschaft des globalen Objektes.

Das Argument der eval() Funktion ist vom Typ string. Wenn der String eine Ausdruck repräsentiert, wird eval() diesen Ausdruck auswerten. Wenn das Argument ein oder mehr JavaScript Anweisungen beinhaltet, wird eval() diese ausführen. Benutze nicht eval() um einen arithmetischen Ausdruck auszuführen; JavaScript wertet arithmetischen Ausdrücke automatisch aus.

Wenn du einen arithmetischen Ausdruck als String konstruierst, kannst du eval() nutzen, um diesen zu einem späteren Zeitpunkt auszuwerten. Beispiel: Stell dir vor du hast die Variable x. Du kannst die Ausführung dieses Ausdrucks zu einem späteren Zeitpunkt verschieben und dabei x hineinbeziehen, indem du den Wert des Strings wiedergibst. Sagen wir mal du ordnest den Rückgabewert von "3 * x + 2" einer Variable zu und rufst diese zu einem späteren Zeitpunkt im Script mit eval() auf.

Wenn das Argumemt von eval() nicht ein String ist, wird eval() den Rückgabewert unverändert wiedergeben. Im folgenden Beispiel ist der String Konstruktor festgelegt, und eval() gibt ein String-Objekt wieder, anstelle diesen String auszuwerten.

eval(new String("2 + 2")); // Rückgabewert ist ein String Objekt mit dem Inhalt: "2 + 2"
eval("2 + 2");             // Rückgabewert: 4

Du kannst diese Limitation umgehen indem du eine generische Weise mit toString() verwendest.

var expression = new String("2 + 2");

If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works at global scope rather than local scope; this means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.

function test() {
  var x = 2, y = 4;
  console.log(eval("x + y"));  // Direct call, uses local scope, result is 6
  var geval = eval;
  console.log(geval("x + y")); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined

Don't use eval needlessly!

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

eval() is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.

There are safer (and faster!) alternatives to eval() for common use-cases.

Accessing member properties

You should not use eval() to convert property names into properties. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with eval:

var obj = { a: 20, b: 30 };
var propname = getPropName();  // returns "a" or "b"

eval( "var result = obj." + propname );

However, eval() is not necessary here. In fact, its use here is discouraged. Instead, use the property accessors, which are much faster and safer:

var obj = { a: 20, b: 30 };
var propname = getPropName();  // returns "a" or "b"
var result = obj[ propname ];  //  obj[ "a" ] is the same as obj.a 

Use functions instead of evaluating snippets of code

JavaScript has first-class functions, which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write:

// instead of setTimeout(" ... ", 1000) use:
setTimeout(function() { ... }, 1000); 

// instead of elt.setAttribute("onclick", "...") use:
elt.addEventListener("click", function() { ... } , false); 

Closures are also helpful as a way to create parameterized functions without concatenating strings.

Parsing JSON (converting strings to JavaScript objects)

If the string you're calling eval() on contains data (for example, an array: "[1, 2, 3]"), as opposed to code, you should consider switching to JSON, which allows the string to use a subset of JavaScript syntax to represent data. See also Downloading JSON and JavaScript in extensions.

Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.

Pass data instead of code

For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in XPath instead of JavaScript code.

Run code with limited privileges

If you must run code, consider running it with reduced privileges. This advice applies mainly to extensions and XUL applications, which can use Components.utils.evalInSandbox for this.


Using eval

In the following code, both of the statements containing eval() return 42. The first evaluates the string "x + y + 1"; the second evaluates the string "42".

var x = 2;
var y = 39;
var z = "42";
eval("x + y + 1"); // returns 42
eval(z);           // returns 42 

Using eval to evaluate a string of JavaScript statements

The following example uses eval() to evaluate the string str. This string consists of JavaScript statements that open an alert dialog box and assign 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 x = 5;
var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0; ";

console.log("z is ", eval(str));

Last expression is evaluated

eval() returns the value of the last expression evaluated.

var str = "if ( a ) { 1+1; } else { 1+2; }";
var a = true;
var b = eval(str);  // returns 2
console.log("b is : " + b);

a = false;
b = eval(str);  // returns 3

console.log("b is : " + b);

eval as a string defining function requires "(" and ")" as prefix and suffix

var fctStr1 = "function a() {}"
var fctStr2 = "(function a() {})"
var fct1 = eval(fctStr1)  // return undefined
var fct2 = eval(fctStr2)  // return a function


Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
Die Definition von 'eval' in dieser Spezifikation.
ECMAScript 2015 (6th Edition, ECMA-262)
Die Definition von 'eval' in dieser Spezifikation.
ECMAScript Latest Draft (ECMA-262)
Die Definition von 'eval' in dieser Spezifikation.

Browser compatibility

Wir konvertieren die Kompatibilitätsdaten in ein maschinenlesbares JSON Format. Diese Kompatibilitätstabelle liegt noch im alten Format vor, denn die darin enthaltenen Daten wurden noch nicht konvertiert. Finde heraus wie du helfen kannst!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Ja) (Ja) (Ja) (Ja) (Ja)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Ja) (Ja) (Ja) (Ja) (Ja) (Ja)

Gecko-specific notes

  • Historically eval() had an optional second argument, specifying an object in whose context the evaluation was to be performed. This argument was non-standard, and was removed from SpiderMonkey in Gecko 1.9.1 (Firefox 3.5). See Bug 442333.

See also