Executing a function passed by name as a string

I’m trying to execute a function based on the result of a prompt. I extract the name of the function as a string from an array of strings. To simplify my code:

// functions abc() and dfg() are defined previously
let modList = [“abc”,”dfg”]; 
let modFunction = ModList[0];
let output = modFunction(string);

Gives me an error modFunction is not a function.

Looking through stack overflow, I see that there is a way to do this using a “window” context which I’m assuming doesn’t exist in Drafts, or through the eval() function. The same code with

let output = eval(modFunction(string))

gives me the same error.

I’m probably doing something wrong but what?

You’re right about “window”. That relates to running javascript in a browser window. THERE it makes sense.

First, eval expects a string. You’re passing something else, namely a function call result. And the function is not defined.
Second, eval is considered dangerous (and bad style by some).
Third, what you seem to want to achieve does not even require eval.

Use an array whose elements are functions (and get the spelling right: modList vs ModList?)

// functions abc() and dfg() are defined previously
let modList = [abc, def]; 
let output = modList[0](string);

(Not tested, though)

1 Like

One issue with this: It’s possible @Seishonagon wanted to display the function names in some way, as well as then letting the user pick from that displayed list.

Unless you know better, it seems to me there have to be two arrays: A function array and a name array.

1 Like

There’s probably an english version of this text, too.
Generally, JavaScript is fairly good at introspection.
And even if there were no name property on the Function object, an array of objects would be preferable over two arrays, I think:

let myFunctions=[{fct: fct1, name: "fct1"}, …];
2 Likes

Thanks @chrillek and @martinpacker.

Yes, I was trying to display a prompt and execute a corresponding function, with a very similar array to the one @chrillek shows.
My mistake was passing a string instead of the actual function. Taking out the quotes worked a treat!
(The mod/Mod mistake was an artifact of my example, not the actual code :slight_smile: )

1 Like

Depending on how you use it, an object of key/value pairs may be more convenient than an array.

// Define fcn1 and fcn2
let myFuncs = {'First Function': fcn1, 'Second Function': fcn2};

// User enters values for f and arg through a prompt
let ans = myFuncs[f](arg);

Thanks @Andreas_Haberle for marking my issues [Solved] - for some reason the entire drafts set of sites was absolutely unavailable to me for the past week…

yep.
I try to keep a clean house to spot the unsolved things or to find them if I am looking for that excavation solutions.

1 Like