JavaScript
Programming
Function Execution
String Manipulation
Coding Tips

How to execute a JavaScript function when I have its name as a string

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Using JavaScript, executing a function when you have its name as a string is a common scenario that developers might encounter, especially when working with dynamic script injections, API data handling, or events. JavaScript provides flexible ways to handle and invoke functions dynamically which are very handy for a variety of applications. Below, we explore several methods to achieve this functionality.

Method 1: Using the eval() Function

The eval() function in JavaScript evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

javascript
1function sayHello() {
2    console.log("Hello!");
3}
4
5let funcName = 'sayHello';
6eval(funcName + '()'); // This will execute the sayHello function

Pros:

  • Extremely versatile and can evaluate any JavaScript code.

Cons:

  • Security risk: if user input is passed to eval(), it can lead to Cross-Site Scripting (XSS) attacks.
  • Difficult to debug and maintain.
  • Generally discouraged to use in modern JavaScript applications due to security issues.

Method 2: Accessing Functions as Object Properties

In JavaScript, functions are first-class objects, which means that you can treat them like any other value - including accessing them as properties of objects.

javascript
1function greet() {
2    console.log("Hello world!");
3}
4
5const functions = {
6    greet
7};
8
9const funcName = 'greet';
10functions[funcName](); // Hello world!

Pros:

  • Safer than eval().
  • Easier to manage and maintain.

Cons:

  • Requires maintaining an object map of references to the actual functions.

Method 3: Using the window or globalThis Object

In a browser environment, global functions are properties of the window object. Similarly, in Node.js, you can use global (or globalThis in newer versions which provides a standard way to access the global object across environments).

javascript
1function displayMessage() {
2    console.log("Displaying message");
3}
4
5let functionName = 'displayMessage';
6window[functionName](); // In a browser

For Node.js:

javascript
1globalThis.displayMessage = function() {
2    console.log("Displaying message from Node.js");
3};
4
5let functionName = 'displayMessage';
6globalThis[functionName](); // In Node.js

Pros:

  • Straightforward in global context.
  • Does not require extra management.

Cons:

  • Not suitable for modular or encapsulated code.
  • Could lead to conflicts in global namespace.

Method 4: Using Function Constructor

Another approach is to use the Function constructor. This is similar to eval() but is less powerful and slightly safer.

javascript
let functionName = "return 'Hello World!';";
let createFunction = new Function(functionName);
console.log(createFunction()); // "Hello World!"

Pros:

  • Safer than eval() since it allows limited access to local scopes.

Cons:

  • Still has some indirect security risks.
  • Less readable and can be harder to maintain than direct function calls.

Summary Table

MethodUse CaseProsCons
eval()General executionVery versatileHigh security risk, hard to debug
Object PropertiesControlled environmentsSafe, easy to maintainRequires setting up an object map
window/globalGlobal function executionEasy to use in global scopeNot suitable for modules, might lead to naming conflicts
Function ConstructorEvaluating stringsSafer alternative to eval()Still risky, less direct and readable

Closing Thoughts

When deciding which method to use, consider the context of your application, the need for security, maintainability, and performance implications. For most applications, using an object properties approach or leveraging globalThis carefully can provide both flexibility and safety. Avoid using eval() and, to a lesser extent, the Function constructor, unless absolutely necessary and you're aware of the potential implications.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms