eval function allows to execute a string of
The syntax is:
let result = eval(code);
A call to
eval returns the result of the last statement.
The code is executed in the current lexical environment, so it can see outer variables:
It can change outer variables as well:
In strict mode,
eval has its own lexical environment. So functions and variables, declared inside eval, are not visible outside:
eval doesn’t have its own lexical environment, so we would see
In modern programming
eval is used very sparingly. It’s often said that “eval is evil”.
eval. But that time passed a decade ago.
Right now, there’s almost no reason to use
Still, if you’re sure you need to dynamically
eval a string of code, please note that its ability to access outer variables has side-effects.
Code minifiers (tools used before JS gets to production, to compress it) replace local variables with shorter ones for brewity. That’s usually safe, but not if
eval is used, as it may reference them. So minifiers don’t replace all local variables that might be visible from
eval. That negatively affects code compression ratio.
Using outer local variables inside
eval is a bad programming practice, as it makes maintaining the code more difficult.
There are two ways how to evade any eval-related problems.
If eval’ed code doesn’t use outer variables, please call
This way the code is executed in the global scope:
If your code needs local variables, execute it with
new Function and pass them as arguments:
new Function construct is explained in the chapter The "new Function" syntax. It creates a function from a string, also in the global scope. So it can’t see local variables. But it’s so much clearer to pass them explicitly as arguments, like in the example above.
A call to
eval(code) runs the string of code and returns the result of the last statement.
- Can access outer local variables. That’s considered bad practice.
- Instead, to
evalthe code in the global scope, use
- Or, if your code needs some data from the outer scope, use
new Functionand pass it as arguments.