W3jar
402 words
2 minutes

How to Execute JavaScript Functions from String Names

Executing JavaScript functions from string names is a common scenario in dynamic programming. You might want to call a function whose name is stored in a variable or received as a string. Here are a few ways to achieve this:

1. Using the window Object (in the Browser)#

In a browser environment, you can use the window object to access global functions by name. This method is straightforward if the function is defined in the global scope.

Example:

function myFunction() {
    console.log("Function executed!");
}

const functionName = "myFunction";
if (typeof window[functionName] === "function") {
    window[functionName](); // Calls myFunction
}

The eval() function can execute code represented as a string. While it can be used to call functions from strings, it’s generally not recommended due to security and performance concerns.

Example:

function myFunction() {
    console.log("Function executed!");
}

const functionName = "myFunction";
eval(functionName + "()");

Note: Use eval() with caution, as it can introduce security vulnerabilities if the string is constructed from untrusted input.

3. Using an Object to Map Function Names to Functions#

A more controlled approach is to use an object as a map where keys are function names and values are the corresponding functions. This is a safer and more maintainable method.

Example:

const functions = {
    myFunction: function () {
        console.log("Function executed!");
    },
    anotherFunction: function () {
        console.log("Another function executed!");
    },
};

const functionName = "myFunction";
if (typeof functions[functionName] === "function") {
    functions[functionName](); // Calls myFunction
}

4. Using Function.prototype.call or Function.prototype.apply#

If you have a function reference and want to call it with specific arguments, you can use .call() or .apply().

Example:

function myFunction(arg1, arg2) {
    console.log(`Function executed with arguments: ${arg1}, ${arg2}`);
}

const functionName = "myFunction";
const functions = {
    myFunction: myFunction,
};

if (typeof functions[functionName] === "function") {
    functions[functionName].call(null, "arg1", "arg2"); // Calls myFunction with arguments
}

5. Using Function Constructor#

The Function constructor can dynamically create functions from strings, but it has similar security concerns as eval() and should be used with caution.

Example:

const functionName = "console.log('Function executed!')";
const dynamicFunction = new Function(functionName);
dynamicFunction();

Summary#

  • Global Scope: Use window[functionName] to call global functions by name.
  • Object Map: Create a mapping object for safer and more controlled access to functions.
  • eval(): Execute code from strings, but avoid using it due to security risks.
  • call / apply: Call functions with specific contexts and arguments.
  • Function Constructor: Create functions dynamically, but be cautious of security implications.

Using an object to map function names to functions is typically the best approach for most use cases due to its clarity and security benefits.