The JavaScript eval() function executes a string as JavaScript. This is a massive security risk as, if used in production, it can allow third parties to execute their own code in your app.
eval() Syntax
eval(string)
Note that:
- string is a string that contains JavaScript Code
- eval() will return the value returned by executing the code in the string
- Just don’t use it
Example of Javascript eval()
This article gets one example only so you can see how eval() works, so that if you accidentally fall on your keyboard and the letters E-V-A-L are miraculously entered into your JavaScript code, you can spot it and remove it.
let test = eval('2 + 2'); // Assign the result of the string as JavaScript to the variable test console.log(test); // Will output 4
What to (not) Use Instead – Function()
If, for some reason, you absolutely must execute JavaScript code from a string variable, use the Function object instead. Here’s the above code adapted to create a Function object which will execute code supplied from a string:
function twoPlusTwo(){ return Function('return (2 + 2);')(); } console.log(twoPlusTwo())
Note that even this method is highly likely to be blocked by your or your users’ web browser.
For the technical details about the Function object, MDN has you covered
Really, you should just avoid trying to execute JavaScript code from strings altogether. If your concept requires it to be done, rethink your code’s structure so that it isn’t required.