The eval() function in JavaScript can run a single expression, a statement, or multiple statements. If you pass an expression, it will be evaluated, and eval() returns its result. If you pass a statement or a block of statements, it simply executes them and returns undefined unless the last statement produces a value.
In this article, you will learn some interesting details about JavaScript’s eval() function. Let’s start simple with its syntax, parameters, and return value.
JavaScript eval() Function Syntax
The eval() is a method of the JavaScript global object that can be directly called anywhere using the below syntax:
eval(string)
What Parameters Does eval in JavaScript Accept?
JavaScript eval takes a single parameter, which is a string. This string can contain a statement, an expression, or a sequence of statements.
What Does the eval Function Return?
eval function returns the completion value and if there is no completion value it will return undefined.
Also Read: Introducing Object.groupBy() and Map.groupBy() in JavaScript
Examples of Executing JavaScript Code with eval
Let’s see some simple examples to demonstrate how to use eval in JavaScript and understand when the eval function makes sense.
Example 1: Evaluate Expression
The below script contains a string that contains a JavaScript expression. Let’s evaluate it using the eval() method and print the output in the console.
const exp = "2 + 2";
const result = eval(exp);
console.log(result);
Output:
4
Here you can see that the expression is successfully evaluated and the eval() method returned the result.
Example 2: Execute Statement
This time the string contains a JavaScript statement to print ‘Hello World’ in the console, showing how eval in JavaScript can execute JavaScript code dynamically.
const sta = 'console.log("Hello World")'
const result = eval(sta);
console.log(result);
Output:
Hello World
undefined
Here you can see that the statement inside the string is successfully executed as we have gotten the “Hello World” in the console but we also have undefined in the output. This is because the last statement has no completion value and we know that when there is no value to return, eval() returns undefined.
Example 3: Execute Multiple Statements
Let’s evaluate a group of statements using the eval() method.
const stas = `let a = 2;
let b = 3;
let sum = a + b;
console.log("Sum is: " + sum);
`;
eval(stas);
Output:
Sum is: 5
The output is correct as 2 + 3 is 5, which means all the statements are successfully executed. We have not got an undefined here as we have not tried to print the value that eval() returns, if we print it then again we will get undefined.
Evaluating a Function in JavaScript Using eval
Directly passing a function inside a string to be evaluated using the eval() method will cause an error.
Let’s try to pass a function declaration inside the string to evaluate it using the eval() method.
const fun = "function sum(a, b) { return a + b; }";
const getFun = eval(fun);
console.log(getFun(2, 3)); // undefined
Output:
console.log(getFun(2, 3)); // undefined
^
TypeError: getFun is not a function
at Object.<anonymous> (C:\Users\ag290\OneDrive\Desktop\eval\app.js:27:13)
at Module._compile (internal/modules/cjs/loader.js:759:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
at Function.Module._load (internal/modules/cjs/loader.js:555:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:826:10)
at internal/main/run_main_module.js:17:11
Here we got an error.
To evaluate a string containing a function using the eval() method, it is required to wrap it properly in a round bracket ():
const fun = "(function sum(a, b) { return a + b; })";
const getFun = eval(fun);
console.log(getFun(2, 3)); // 5
Output:
5
Here we got the expected result, so next time you try it, don’t forget to wrap your function inside (), before executing it.
Security Risks of Running Malicious Code with eval
In the early days of JavaScript, eval() might have been a good choice to execute dynamic code based on user input or other conditions. But in modern JavaScript, it is not advisable to use eval().
Using eval() is a dangerous function and a security risk because code being evaluated can access local variables within the scope where it’s being called and even run arbitrary third-party code.
Instead of using eval(), you can often achieve the same result with safer alternatives. For string interpolation, use template literals. If you truly need to generate and run code dynamically, the Function constructor is a better option than eval().
The Takeaway
Eval means evaluate, as the name suggests, the eval() function in JavaScript is used to evaluate or parse a sequence of statements or a JavaScript expression inside a string and return the completion value. If there is no completion value, it returns undefined. While it can be used to execute dynamic code or run arbitrary code snippets, it is considered a dangerous function because the code being evaluated doesn’t have access to local variables within strict mode and instead runs in the global scope rather than the scope where it’s being called. This makes it slower than the alternatives and vulnerable to injection attacks.
Using eval() with user input can cause major security risks, as malicious code may execute JavaScript directly, access variables and objects, or overwrite variables or functions unexpectedly. Since eval uses the global scope, an indirect call or direct call can change how the interpreter runs the code, leading to unexpected behavior. Developers might occasionally use eval for debugging or quick tests, but a safer use case would be to use the Function constructor, setTimeout, or parse as JSON when working with dynamic content.
In short, while eval() can execute JavaScript dynamically and even handle third-party code, it’s rarely justified in modern applications. Be careful when using eval: the code can see the scope, lead to possible attacks, and run arbitrary code. It’s better to avoid eval and rely on safer alternatives that respect scope and provide more predictable results.
Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval