How to execute a JavaScript function when I have its name as a string
Leverage the bracket notation and global context object (window
for browsers, global
for Node.js) to execute a JavaScript function from a string name:
Note, the optional chaining operator (?.
) provides safety (it calls echo
only if it's a function). For security, steer clear of eval
.
When dealing with non-global contexts, use the Function constructor:
Remember to populate context
with your function for a successful execution within your intended scope.
Diving deeper into dynamic execution
The fast answer covers most use cases, but the rabbit hole goes much deeper. Let's traverse it, exploring advanced scenarios and optimal practices for invoking JS functions from string names.
Namespace navigation
When handling namespaced functions, consider this pattern:
ES6 computed magic
For computed property names in ES6 to avoid magic strings when dealing with dynamically named functions within an object:
Frozen function hash
Maintain the integrity of your functions in a hash object using Object.freeze
. Elsa from Frozen would be proud:
A controlled yet dynamic approach
Taking a more controlled approach, we can also write a helper function:
Securing your code
Always maintain the highest security standards to eliminate any potential injection attacks and prevent bugs wearing sunglasses!
Emphasizing on context
Ensuring that the context is correct is crucial when using dynamically allocated functions.
Always ensure that the context is preserved to avoid the regular not what I meant to do programming scenario.
Against the 'eval' dark forces
While eval
and Function()
seem like great options for executing dynamic code, they can be security landmines, leading to XSS attacks. Approach with caution, like a snake pit or pineapple pizza.
Proxies to the rescue
For capturing function calls dynamically, ES6 Proxies act as a security camera:
Was this article helpful?