The JavaScript eval()
function is used to execute a piece of JavaScript code and return the value obtained from executing that code.
You need to wrap your JavaScript code as a string as follows:
console.log(eval("2 + 2")); // 4
When you pass either an expression as in the example above, or a statement as seen below:
// undefined because statement doesn't produce value
console.log(eval('let declaredVariable = 7')); // undefined
Should you use eval() function?
The eval()
function is created so that you can turn a string
into an executable JavaScript code. This means you can receive a piece of JavaScript code sent from a remote server as text and actually execute it on your machine.
But it’s also dangerous because JavaScript can’t control the privileges of an eval()
operation, meaning if the string
contains code that manipulates your database, then there’s no way to stop that code.
This is why the eval()
function is considered evil and should be avoided.