W3docs

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

Read this tutorial and learn about the safe method of calling a function when you have its name as a string. Also, read about why you should not use eval().

In this tutorial, we will discuss the two methods that are used to execute a function from string stored in a variable. Let’s discuss which method is preferable and safe for this kind of situation.

The window object in HTML5 references the current window and all items within it. You can use it to run a function specified as a string along with its parameters:

JavaScript function when you have its name as a string

window["functionName"](arguments);

As this will not work with a namespace'd function you can use the following:

JavaScript function when you have its name as a string

window["Namespace"]["functionName"](arguments); // succeeds

Here we suggest a flexible example:

JavaScript function when you have its name as a string

javascript— editable

You can call it like this:

JavaScript function when you have its name as a string

executeFunctionByName("Namespace.functionName", window, ['arg1', 'arg2']);

There is another method that is used often to resolve such situations, namely, eval(). However, be aware that using this method is not recommended. Let’s explain why you should not use this method.

The major reason you should avoid using it is that it poses security risks, hinders performance optimization, and complicates debugging. Instead, we suggest a better and safer solution to your problem at the beginning of the tutorial.