Home » Programming » Javascript » Javascript Eval

Javascript eval() Function (and Why to NEVER Use It)

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


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);')();

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.

Photo of author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment