Skip to content
Amal Hashim
All posts
Snippet

JavaScript: invoke a function by name from a string variable

Look the function up on window using its name, check it is a function, then call it with apply.

1 min read#JavaScript#jQuery

When building dynamic forms you may need to call a JavaScript function whose name is stored in a variable. Global functions are properties of window, so you can look the name up there.

js
var functiontocall = "HelloWorld";
var fn = window[functiontocall];
if (typeof fn !== 'function')
    return;
var retvalue = fn.apply(window, ["Amal Hashim"]);

The function being called:

js
function HelloWorld(name) {
    return "Hello " + name;
}

The typeof check stops the call if the name does not match a function.

Example

With the code above, retvalue is:

text
Hello Amal Hashim