23
loading...
This website collects cookies to deliver better user experience
eval()
and Function()
in JavaScript.eval()
and Function()
are two powerful tools in JavaScript that both allow you to evaluate any JavaScript expression passed to either of them as a string. They are both used for the same thing, though they differ in how they handle your expression.eval()
.eval()
is a global function which takes a JavaScript expression as a string and executes it. It does not return anything except undefined
. If you write some script into your HTML and use eval()
, you will notice the output gets printed to the console while in an environment like node, you will want to use console.log()
. This is because it tend to pipe the result of an expression for example to standard output or an equivalent.eval()
saves you time. Just pass what the user inputs to eval and let the magic.let userInput = "2+4";
eval(userInput); // output : 6
Function()
. Just like eval(), it takes some expression as a string for execution except rather than outputing the result directly, it returns to you an anonymous function which you can call. It is a faster and more secure alternative to eval(). Let us try the same example as above but with Function()
.let userInput = "2+4";
let result = Function(userInput);
function anonymous() {
2+4
}
Function()
returns to us an anonymous function. Looking more, we can see that the expression we passed in the string is found in the function body. let userInput = "2+4";
let result = Function("return " + userInput); // which is same as "return 2+4"
function anonymous() {
return 2+4
}
let userInput = "2+4";
let result = Function("return " + userInput)(); // which is same as "return 2+4"
eval()
and Function()
are really powerful tools we have at hand in JavaScript. But that power comes at a price. Arbitrary code can be executed by a technical enough user or malicious individual.eval()
is particularly dangerous. This is because it allows one to execute code with the same privileges as the caller of eval()
. Say you create an app that evalues some code and stores the result on the user's machine using the FileApi in the browser. The user can use eval()
against your app and get access to FileAPI too to carry out malicious tasks.eval()
is much slower than Function()
.eval() is also slower than the alternatives, since it has to invoke the JavaScript interpreter, while many other constructs are optimized by modern JS engines.
Additionally, modern javascript interpreters convert javascript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of eval() will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. Additionally, new things can be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate.