eval() vs. Function() in JavaScript
Last Updated :
19 Apr, 2024
We will learn about
JavaScript functions
eval()
and Function().
The eval()
and Function()
are used to evaluate any JavaScript expression passed to either of them as a string but the difference between them is how how they handle the expression.
eval()
The eval() method in JavaScript evaluates or executes its argument. If the argument is an expression, it evaluates the expression. If it’s one or more JavaScript statements, eval() executes the statements.
Syntax:
eval(String)
Example: In this example, we use `eval()` to evaluate the multiplication expression of `a` and `b`, converting the result to a string.
JavaScript
// JavaScript to illustrate eval() function
function func() {
// Original string
let a = 4;
let b = 4;
// Finding the multiplication
let value = eval(new String(a * b));
console.log(value);
}
// Driver code
func();
Function()
The Function()
constructor creates a new function object dynamically from a string representing JavaScript code. It allows us to define functions programmatically at runtime. The code inside the string is compiled when the function is created, not when it is called.
Syntax:
new Function([arg1, arg2, ...argN], functionBody)
Example: In this example, we use the Function()
constructor to create a new function that multiplies two numbers.
JavaScript
// JavaScript to illustrate Function() constructor
// Define a string containing JavaScript code
const code = 'return 4 * 4;';
// Create a new function using Function() constructor
const multiply = new Function(code);
// Execute the dynamically created function
const result = multiply();
console.log(result); // Output: 16
Difference between eval() vs. Function() in JavaScript
Feature | eval() | Function() |
---|
Usage | Evaluates JavaScript code as a string | Creates a new function from a string of code |
---|
Scope | Runs code in the current lexical scope | Creates a new function with its own lexical scope |
---|
Performance | Generally slower due to parsing and execution | Can be faster since code is compiled upfront |
---|
Security | Considered risky due to potential security issues | Generally safer as it creates a new function object |
---|
Dynamic code | Suitable for executing dynamic code | Suitable for generating functions dynamically |
---|
Syntax Errors | May not throw syntax errors immediately | Throws syntax errors at creation time |
---|
Syntax
| eval(String)
| new Function([arg1], functionBody)
|
---|
Share your thoughts in the comments
Please Login to comment...