The syntax of the eval() function is the following:
let result = eval(code);
For a better perception, you can check out the following example:
Eval is considered a function property of the global object.
As a rule, the eval() function’s argument is a string. In case the latter presents an expression, eval()will evaluate it. In case an argument presents one and more statements, then eval()will evaluate the statements.
Such a limitation can be worked around with the help of toString() like this:
Generally, eval’s result is equivalent to the result of the last statement. It is demonstrated below:
In case the code is executed within the current lexical environment, outer variables can be seen by it:
In addition, those variables can be modified by it:
Eval has its own lexical environment in the strict mode. So, no one can see the functions and variables, declared in it:
Be Careful with Eval!
It is essential to note that eval() is quite a dangerous function. That’s why in modern programming the phrase “eval is evil” is so actual. So, using it is a bad practice for a programmer.
In case you run it with a string, which may be impacted by a malicious party, it can lead to malicious code on the user’s device with the permissions of your page or extensions.