JavaScript eval

eval() is a global function in JavaScript that evaluates a specified string as JavaScript code and executes it.

Example: eval
eval("alert('this is executed by eval()')");

The eval() function can also call the function and get the result as shown below.

Example: eval
var result;

function Sum(val1, val2)
    return val1 + val2;

eval("result = Sum(5, 5);");


eval can convert string to JSON object.

Example: eval with JSON Object
var str = '({"firstName":"Bill","lastName":"Gates"})';

var obj = eval(str);

obj.firstName; // Bill 


It is not recommended to use eval() because it is slow, not secure, and makes code unreadable and maintainable.