How to useeval() Method in Javascript

The eval() method is a powerful but often discouraged feature of JavaScript that allows you to execute arbitrary code as a string. You can use eval() to execute a JavaScript function when you have its name as a string.

Syntax:

function myFunction() {
...
}
const functionName = "myFunction";
eval(functionName + "()");

Example: In this example, we define a function greet that logs a greeting to the console, and a variable functionName with the value “greet”, which is the name of the function. Then we use eval() method to execute the function by constructing a string of code that calls the function by name, passing in the argument “Alice”. This results in the greet function being executed, and the output “Hello, Alice!” being logged to the console.

Javascript




function greet(name) {
      console.log(`Hello, ${name}!`);
}
 
const functionName = "greet";
 
// Using eval() to execute the function
eval(`${functionName}("Alice")`);


Output

Hello, Alice!

How to execute a function when its name as a string in JavaScript ?

To execute a function when its name is a string in JavaScript, we have multiple approaches. In this article, we are going to learn how to execute a function when its name is a string in JavaScript.

Example:

function myFunction() {
...
}
const functionName ="myFunction";

Below are the approaches used to execute a function when its name is a string in JavaScript:

Table of Content

  • Using eval() Method
  • Using window[]
  • Using Function constructor

Similar Reads

Approach 1: Using eval() Method

The eval() method is a powerful but often discouraged feature of JavaScript that allows you to execute arbitrary code as a string. You can use eval() to execute a JavaScript function when you have its name as a string....

Approach 2: Using window[]

...

Approach 3: Using Function constructor

In a browser environment, you can use the window[] syntax to execute a JavaScript function when you have its name as a string....

Contact Us