Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Convert String to Function Name in JavaScript

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You cannot turn a string into a function name directly in JavaScript, but you can call a function by its string name using the global object, a lookup object, or eval (not recommended). The safest and most common approach is to store your functions in an object and access them with bracket notation: myFunctions["functionName"](). This guide shows you exactly how to do that, plus the pitfalls and best practices.

What You'll Need

  • A basic understanding of JavaScript functions and objects.
  • A code editor or browser console to test the examples.
  • No special libraries — everything here is built into JavaScript.

Step-by-Step

  1. Understand why you need a lookup object. In JavaScript, functions are values. You can store them as properties of an object, then retrieve them using a string key. This avoids using eval and works in strict mode.
  2. Create an object to hold your functions. For example:
    const actions = {
      greet: function(name) { return 'Hello, ' + name; },
      farewell: function(name) { return 'Goodbye, ' + name; }
    };
  3. Get the function name as a string. This might come from user input, a data attribute, or a configuration file. For example: const fnName = 'greet';
  4. Check that the function exists. Use typeof actions[fnName] === 'function' before calling it to avoid errors.
  5. Call the function using bracket notation. actions[fnName]('Alice') returns 'Hello, Alice'. If the function needs arguments, pass them after the parentheses.
  6. Handle missing functions gracefully. If the string doesn't match any key, provide a fallback or throw a clear error. Example:
    if (typeof actions[fnName] === 'function') {
      actions[fnName]('Alice');
    } else {
      console.error('Unknown function:', fnName);
    }
  7. For global functions, use the window object (browser only). If your function is declared globally (e.g., function myFunc() {}), you can call it with window['myFunc'](). This does not work in Node.js or in modules where functions are not global.
  8. Avoid eval and new Function. They execute arbitrary code and are a security risk. Use the object lookup pattern instead.
  9. Test your implementation. Run your code in the console or a test file to confirm that strings map to the correct functions and that invalid names are handled.

Common Mistakes

  • Using eval with user input. This can lead to code injection. Always prefer a lookup object.
  • Assuming global functions are always available. In ES modules or strict mode, functions are not attached to window.
  • Forgetting to check if the function exists. Calling actions[fnName]() when fnName is undefined throws a TypeError.
  • Using dot notation with a variable. actions.fnName looks for a property literally named "fnName", not the value of the variable. Use brackets: actions[fnName].
  • Overwriting built-in methods. If your object inherits from Object.prototype, a string like 'toString' could call the built-in method. Use Object.create(null) or check hasOwnProperty to avoid this.

Tips

  • Use Object.hasOwn(actions, fnName) (modern) or actions.hasOwnProperty(fnName) to ensure the property belongs to your object, not its prototype.
  • Keep your lookup object in a module scope to avoid polluting the global namespace.
  • If you need to call functions dynamically from a string in a safe way, consider a Map: const actions = new Map(); actions.set('greet', fn); then actions.get(fnName)?.().
  • For event handlers or callbacks, you can also use window[handlerName] if the function is global, but the object pattern is more maintainable.
  • Always validate and sanitize the string if it comes from an untrusted source to prevent unexpected function calls.

Troubleshooting

If your function call fails, check these common issues:

  • "actions[fnName] is not a function" — the property exists but is not a function, or the name is misspelled. Log typeof actions[fnName].
  • "Cannot read property 'call' of undefined" — the function name doesn't exist in the object. Verify the key with Object.keys(actions).
  • Function works in console but not in your script — likely a scope issue. Ensure the object is defined before you try to access it.
  • Using window[fnName] returns undefined — the function might be declared inside a module or block scope, not globally. Move it to the global scope or use an object.
  • Unexpected behavior with inherited properties — use Object.create(null) for your lookup object or check with hasOwnProperty.

Frequently Asked Questions

Can I convert a string to a function name without an object?

Only if the function is global (attached to window in browsers). In that case, window[stringName] works. For all other cases, use a lookup object.

Is using eval safe for this?

No. eval executes arbitrary code and is a security risk, especially with user input. Avoid it entirely.

What about new Function?

It's similar to eval and should be avoided for the same reasons. Use a lookup object instead.

How do I call a function by string name in Node.js?

Use a lookup object. Global functions are not attached to global in the same way as window in browsers, and relying on that is fragile.

Can I use a string to call a method on an object?

Yes, with bracket notation: obj['methodName'](). Just ensure the method exists and is a function.

What if the string contains special characters?

Bracket notation handles any string key, including those with spaces or special characters, as long as the property name matches exactly.