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.

<!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>