Convert String to Function Name in JavaScript
In this article
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
- 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
evaland works in strict mode. - Create an object to hold your functions. For example:
const actions = { greet: function(name) { return 'Hello, ' + name; }, farewell: function(name) { return 'Goodbye, ' + name; } }; - 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'; - Check that the function exists. Use
typeof actions[fnName] === 'function'before calling it to avoid errors. - Call the function using bracket notation.
actions[fnName]('Alice')returns'Hello, Alice'. If the function needs arguments, pass them after the parentheses. - 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); } - For global functions, use the window object (browser only). If your function is declared globally (e.g.,
function myFunc() {}), you can call it withwindow['myFunc'](). This does not work in Node.js or in modules where functions are not global. - Avoid
evalandnew Function. They execute arbitrary code and are a security risk. Use the object lookup pattern instead. - 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
evalwith 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]()whenfnNameis undefined throws a TypeError. - Using dot notation with a variable.
actions.fnNamelooks 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. UseObject.create(null)or checkhasOwnPropertyto avoid this.
Tips
- Use
Object.hasOwn(actions, fnName)(modern) oractions.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);thenactions.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 withhasOwnProperty.
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.