Is it possible to execute a function using eval?

I have a scenario, where I accept huge functions script in the string and need to execute it in real time. A simple example of it is as follows...

var fn = "function(){}";
eval(fn);

However, I am getting an error for the above script. Is there a way that I can do this or is it totally discouraged?

2 answers

  • answered 2018-02-13 00:58 Michael Saunders

    var fn = "function(){}";
    eval("(" + fn + "())");
    

    Or, if you want to define the function so it can be called later:

    var fn = "function(){}";
    eval("fn = " + fn);
    fn();
    

  • answered 2018-02-13 01:07 visibleman

    Are you simply looking for a function constructor from string, then you can do this without eval.

    // Using eval
    eval("var evalfn=function(){console.log('in evalfn'); return 11}");
    var ret1 = evalfn();
    console.log("eval ret1:" + ret1);
    
    // Using new Function() without arguments
    var fn = new Function("console.log('in fn'); return 12");
    var ret2 = fn();
    
    console.log("fn ret2:" + ret2);
    
    // Using new Function() with arguments
    var fnwithargs = new Function("a", "b", "console.log('in fnwithargs'); return a+b");
    var ret3 = fnwithargs(10, 5);
    
    console.log("fnwithargs ret3:" + ret3);

    Notice that with this technique, your strings cannot contain the keyword function(). Instead you provide variable names and the function body to the Function constructor.