How to Execute a JavaScript Function when You have Its Name as a String

JavaScript is a dynamic language that allows you to store functions as variables and pass them around as arguments to other functions.

However, there may be scenarios where you have a string that represents the name of a function and you want to execute it.

This Javascript tutorial will explain how to do that.


Using eval()

The eval() function is a powerful function in JavaScript that can execute a string as code.

This means that you can use eval() to execute a string that represents the name of a function.

Here’s an example:

function sayHello() {
  console.log('Hello World!');
}

const funcName = 'sayHello';

eval(funcName + '()'); 

This code will execute the sayHello() function because the eval() function evaluates the string funcName + '()' as code and calls the sayHello() function.

However, it’s important to note that the use of eval() is generally discouraged due to security and performance concerns.

Using the window object

The window object in JavaScript represents the global scope, and all global variables and functions are properties of the window object.

This means that you can use the window object to call a function from a string. Here’s an example:

function sayHello() {
  console.log('Hello World!');
}

const funcName = 'sayHello';

window[funcName](); 

This code will execute the sayHello() function because the expression window[funcName] accesses the sayHello() function as a property of the window object and calls it.

Using the Function() constructor

The Function() constructor in JavaScript allows you to create a new function dynamically.

You can use the Function() constructor to call a function from a string by passing the string as an argument to the constructor.

Here’s an example:

function sayHello() {
  console.log('Hello World!');
}

const funcName = 'sayHello';

const func = new Function(funcName + '()');
func(); 

This code will execute the sayHello() function because the expression new Function(funcName + '()') creates a new function that calls the sayHello() function.


Conclusion

In this tutorial, we have seen three methods for calling a JavaScript function from a string.

The eval() function can be used to execute a string as code, but its use is generally discouraged due to security and performance concerns.

The window object and the Function() constructor can be used to call a function from a string without using eval().

Which method you choose will depend on your specific use case and the trade-offs you are willing to make.