Tuesday, September 24, 2024
Google search engine
HomeLanguagesJavascriptHow to execute a function when its name as a string in...

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

In this article, we will see how to execute a JavaScript function named as a string format.

For example:

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

In the above code, functionName is a string and has “myFunction” as its value. Now we have to run the function myFunction using functionName which is a string. So in this article, we are going to see how to solve this problem.

There are several ways to execute a JavaScript function when you have its name as a string.

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.

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!

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

Syntax:

function myFunction() {
    ...
}
const functionName = "myFunction";
window[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. We then use window[functionName] to access the function by its name as a string, and call it with 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 window[] to execute the function
window[functionName]("Alice");


Output:

Hello, Alice!

Approach 3: Using Function constructor: You can create a new function object using the Function constructor, passing in the function name as a string, and then call that new function object. 

Syntax:

function myFunction() {
    ...
}
const functionName = "myFunction";
const fn = new Function(`return ${functionName}()`);
fn();

Example: In this example, we define three variables: functionName with the value “greet”, which is the name of the function, functionArguments with the value “name”, which is the name of the function’s argument, and functionBody with the value “console.log(‘Hello, ‘ + name + ‘!’);” which is the body of the function. We then use the Function constructor to create a new function dynamically with the given arguments and body and store it in a variable dynamicFunction.

Javascript




const functionName = "greet";
const functionArguments = "name";
const functionBody = 
    `console.log('Hello, ' + name + '!');`;
  
// Using the Function constructor 
// to create and execute the function
const dynamicFunction = 
    new Function(functionArguments, functionBody);
dynamicFunction("John");


Output:

Hello, John!

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments