Home » Web » Javascript » Dynamic function in Javascript

Dynamic function in Javascript

In some occasion, calling a dynamic function in Javascript can be useful. This is the case when you have a string that represent the name of the function that you want to execute. One way to do it it to use the EVAL keyword in Javascript. It’s not the best way to do it, but it’s the more known by developer. It let you evaluate Javascript in a string format. That mean that anything given to that function is executed on the client browser. This open a door to malicious code that could be executed if not well used. This is why, I’ll show you a second approach that will not use the EVAL key work to execute dynamic method in Javascript.

First of all, here is an example of code that execute a dynamic function with the EVAL keyword.

function myFunction
{
   alert('Test');
}

var functionName = "myFunction";							//Dynamic builded
var functionParameter = "firstParameter, secondParameter";	//Dynamic parameters
 
var functionToCall = functionName + "('" + functionParameter + "');";
var ret = eval(functionToCall);

As you can see, we could had some kind of logic to choose the functionName. This could have been generated by the server side or could have been loaded from the database or a Web Service. The dangerous part is that someone could change the functionName to direct Javascript statements that could harm the user.

Second, here is better approach that consist to use the window object to call the method. This, atleast, ensure that we are calling a function and not any Javascript statement. Howerver, it’s still possible to be hacked and to executed harmful code.

function myFunction
{
   alert('Test');
}

var functionName = "myFunction";							//Dynamic builded
var functionParameter = "firstParameter, secondParameter";	//Dynamic parameters
 
var functionToCall = window[functionName];
var ret = functionToCall(functionParameter);

In both case, the important thing is not to EVAL data that has been inputted by the user. The executed dynamic code in Javascript must be generated by the developper that has build the system only.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

2 Responses so far.

  1. tejas tank says:

    not good solution.

    Instead of this, use window.

    window[‘functionname’](argument……)

    • Hi tejas,

      As you can read in the second snippet of code you will see that I am using window[‘functionName’] as you suggest. This is the goal of the blog post telling multiple suggestion and the one I am suggesting at the end is the one that is not using Eval.

      Thank you for your comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.