2 Example(s) of JavaScript eval function


Description :

eval() is a function which will be used to evaluate expression and argument of the eval() function is a string. In this example we are evaluating 3 example x * y, 2+2 and x+17 which will result in 600,4 and 37.


JavaScript eval function Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>
<button onclick="evaluateExpression()">Evaluate expression</button>
<p id="sample"></p>
<script>
function evaluateExpression() {
    var x = 20;
    var y = 30;
    var a = eval("x * y") + "<br>";
    var b = eval("2 + 2") + "<br>";
    var c = eval("x + 17") + "<br>";
    var d = eval("18 + y") + "<br>";
    var result = a + b + c +d;
    document.getElementById("sample").innerHTML = result;
}
</script>
</body>
</html>

Output

Description :

In this example of eval(), we have take a string expression and eval it based on condition, At first, a is true and eval(str) will return 2 after printing 2, we are setting a to false and after that eval(str) will return 3.


JavaScript eval function Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>
<body>

<button onclick="evaluateCode()">Evaluate expression</button>
<p id="sample1"></p>
<p id="sample2"></p>
<script>
function evaluateCode() {
     var str = "if ( a ) { 1+1; } else { 1+2; }";
 var a = true;
var b = eval(str);  
 document.getElementById("sample1").innerHTML = b;
a = false;
b = eval(str);  
    document.getElementById("sample2").innerHTML = b;
}
</script>
</body>
</html>

Output