What is the use of JavaScript eval function?

The JavaScript eval() function executes a string as JavaScript code. While powerful, it's generally discouraged due to performance and security concerns.

Syntax

eval(string)

Parameters

string: A string representing a JavaScript expression, statement, or sequence of statements.

Return Value

Returns the completion value of evaluating the given code. If the completion value is empty, undefined is returned.

Basic Example

<html>
<body>
    <script>
        var a = 30;
        var b = 12;
        var res1 = eval("a * b");
        var res2 = eval("5 + 10");
        
        document.write("Result 1: " + res1 + "<br>");
        document.write("Result 2: " + res2 + "<br>");
        
        // Evaluating expressions
        var expression = "Math.pow(2, 3)";
        var result = eval(expression);
        document.write("2^3 = " + result);
    </script>
</body>
</html>
Result 1: 360
Result 2: 15
2^3 = 8

Dynamic Code Execution

<html>
<body>
    <script>
        // Dynamic variable creation
        eval("var dynamicVar = 'Hello World'");
        document.write(dynamicVar + "<br>");
        
        // Dynamic function execution
        var operation = "Math.max(10, 20, 5)";
        var maxValue = eval(operation);
        document.write("Maximum: " + maxValue + "<br>");
        
        // Conditional execution
        var condition = "true";
        if (eval(condition)) {
            document.write("Condition is true");
        }
    </script>
</body>
</html>
Hello World
Maximum: 20
Condition is true

Security Risks

eval() poses significant security risks, especially with user input:

// DANGEROUS - Never do this with user input
var userInput = "alert('XSS Attack!')"; // Could be malicious
eval(userInput); // Executes arbitrary code

Performance Issues

eval() is slower because:

  • Code must be parsed at runtime
  • JavaScript engine optimizations are disabled
  • Creates new execution context

Safer Alternatives

Use Case Instead of eval() Use This
Parse JSON eval('(' + jsonString + ')') JSON.parse(jsonString)
Dynamic property access eval('obj.' + propName) obj[propName]
Mathematical expressions eval(mathString) Function constructor or math libraries

Conclusion

While eval() can execute dynamic JavaScript code, it should be avoided due to security vulnerabilities and performance issues. Use safer alternatives like JSON.parse() or bracket notation for most use cases.

Updated on: 2026-03-15T21:47:12+05:30

426 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements