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

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.

It is recommended to use the window object in HTML5 references the current window and all items within it. You can use the object to run a function in a string along with parameters to the function:

window["functionName"](arguments);

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

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

Here we suggest a flexible example:

func = function( args ) {
    console.log( 'Global function passed:' );
    for( let i = 0; i < arguments.length; i++ ) {
        console.log( '-> ' + arguments[ i ] );
    }
};
nameSpace = {};
nameSpace.func = function( args ) {
    console.log( 'Namespace function passed:' );
    for( let i = 0; i < arguments.length; i++ ) {
        console.log( '-> ' + arguments[ i ] ); 
    }
};
name = 'nameSpacefunc';
n_s_func = [ 'Snowden' ];
noSuchAgency = function(){};

function executeFunctionByName( functionName, context /*, args */ ) {
    let args, namespaces, fn;
    if( typeof functionName === 'undefined' )
    {
        throw 'function name not specified'; 
    }
    if( typeof eval( functionName ) !== 'function' ) {
        throw functionName + ' is not a function'; 
    }
    if( typeof context !== 'undefined' ) { 
        if( typeof context === 'object' && context instanceof Array === false ) { 
            if( typeof context[ functionName ] !== 'function' ) {
                throw context + '.' + functionName + ' is not a function';
            }
            args = Array.prototype.slice.call( arguments, 2 );
        } else {
            args = Array.prototype.slice.call( arguments, 1 );
            context = window;
        }
    } else {
        context = window;
    }
    namespaces = functionName.split( "." );
    fn = namespaces.pop();
    for( let i = 0; i < namespaces.length; i++ ) {
        context = context[ namespaces[ i ] ];
    }
    return context[ fn ].apply( context, args );
}
executeFunctionByName( 'func' );
executeFunctionByName( 'func', 100 );
executeFunctionByName( 'nameSpace.func', 'No Such Agency!' );
executeFunctionByName( 'func', nameSpace, 'No Such Agency!', [ 008, 'is the even' ] );
executeFunctionByName("nameSpace.func", window, arguments);

You can call it like this:

executeFunctionByName("Namespace.functionName", window, arguments);

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 and the first reason you should avoid using it is that the method is obsolete and may not be supported by newer browsers. It has some safety, optimization and debugging issues. Instead, we suggest a better and safer solution to your problem at the beginning of the tutorial.

Do you find this helpful?

Related articles