Open In App

eval() vs. Function() in JavaScript

Last Updated : 19 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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();

Output
[String: '16']

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

Output
16

Difference between eval() vs. Function() in JavaScript

Featureeval()Function()
UsageEvaluates JavaScript code as a stringCreates a new function from a string of code
ScopeRuns code in the current lexical scopeCreates a new function with its own lexical scope
PerformanceGenerally slower due to parsing and executionCan be faster since code is compiled upfront
SecurityConsidered risky due to potential security issuesGenerally safer as it creates a new function object
Dynamic codeSuitable for executing dynamic codeSuitable for generating functions dynamically
Syntax ErrorsMay not throw syntax errors immediatelyThrows syntax errors at creation time

Syntax

eval(String)

new Function([arg1], functionBody)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads