JavaScript eval

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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

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 

Recommendation:

It is recommended not to use eval() because it is:

  1. Slow
  2. Not secure
  3. Not readable and maintainable