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


There are a few ways to execute a function when its name is given as a string in JavaScript:

  • Using the window object: If the function is defined in the global scope, you can use the window object to execute it. Here's an example:
   function myFunction() {
     console.log("Hello World!");
   }

   const functionName = "myFunction";
   window[functionName](); // Output: "Hello World!"
  • Using eval(): The eval() function can be used to execute a string as JavaScript code. Here's an example:
   function myFunction() {
     console.log("Hello World!");
   }

   const functionName = "myFunction";
   eval(functionName + "()"); // Output: "Hello World!"

Note: Using eval() can be dangerous if the string being evaluated is not trusted, as it can execute arbitrary code.

  • Using the Function constructor: The Function constructor can be used to create a new function from a string, which can then be executed. Here's an example:
   const functionName = "function myFunction() { console.log('Hello World!'); }";
   const fn = new Function(functionName);
   fn(); // Output: "Hello World!"

Note: Using the Function constructor can also be dangerous if the string being evaluated is not trusted, as it can execute arbitrary code.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.