Javascript Reference - JavaScript eval() Function








The eval() function evaluates or executes an argument.

eval() works like an interpreter and accepts a string of JavaScript to execute.

eval("console.log('hi')");

This line is functionally equivalent to the following:

console.log("hi");

When the interpreter finds an eval() call, it interprets the argument into actual ECMAScript statements and then inserts it into place.

Code executed by eval() is considered to be part of the execution context in which the call is made.

Variables defined in the containing context can be referenced inside an eval() call.

var msg = "hello world";
eval("console.log(msg)");    //"hello world"

You can define a function or variables inside an eval() call that can be referenced by the code outside.

eval("function sayHi() { console.log('hi'); }");
sayHi();
eval("var msg = 'hello world';");
console.log(msg);  //"hello world"

In strict mode, variables and functions created inside of eval() are not accessible outside.





Browser Support

eval Yes Yes Yes Yes Yes

Syntax

eval(string)

Parameter Values

Parameter Description
string A JavaScript expression, variable, statement, or sequence of statements

Example

The following code shows how to Evaluate/Execute JavaScript code/expressions.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!--from w w  w.ja v a  2 s.c o m-->
<p id="demo"></p>

<script>
function myFunction() {
    var x = 10;
    var y = 20;
    var a = eval("x * y") + "<br>";
    var b = eval("2 + 2") + "<br>";
    var c = eval("x + 17") + "<br>";

    var res = a + b + c;
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>

The code above is rendered as follows: