How to call a function from its name stored in a string using JavaScript?


We will use the eval() function to call a function from its name stored in a string. The eval() function evaluates a string as JavaScript code. This allows us to call the function by passing the string containing its name as an argument to the eval() function.

Example

Here is a complete working example of how to call a function from its name stored in a string using JavaScript −

// Define the function that we want to call
function sayHello() {
   console.log("Hello, world!");
}

// Store the function name as a string
let functionName = "sayHello";

// Use the `eval()` function to convert the string to a function call
eval(functionName + "()");
  • In the above example, we first define a simple function called sayHello() that simply logs “Hello, world!” to the console. Next, we define a variable called functionName that stores the string “sayHello”, which is the name of the function we want to call.

  • Finally, we use the eval() function to convert the string functionName into a function call by concatenating it with the parentheses () that are necessary to actually call the function.

  • The eval() function is a powerful but potentially dangerous feature of JavaScript that allows you to evaluate a string as if it were JavaScript code. It is generally not recommended to use eval() in production code because it can be used to execute arbitrary code, which can be a security risk.

Alternate approach

It is worth mentioning that there are more safe ways to call function from its name stored in string without using eval like −

let functionName = "sayHello";
let functionObj = window[functionName];
functionObj();

Or

let functionName = "sayHello";
let functionObj = window['sayHello'];
functionObj();

These alternatives are safer than using eval because they don’t execute arbitrary code and instead reference the function directly by its name.

Updated on: 16-Feb-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements