-2

That's about it. I have a string = "sum" and a function named sum(a,b), how can I substitute my string to call that function;

string = "sum"
function sum(a,b)

So basically to call that function, I would want to execute it like

string(a, b)
1
  • Geez got downvoted for asking an existing question. Thanks for the help tho and pointing me to the right direction, still appreciate the help. Commented Aug 31, 2020 at 12:24

1 Answer 1

1

I suggest you use dictionary, where you define all existing functions:

const funcs = {
    sum: function(a, b) {

    },
    someStuff: function(r, f) {

    }
};
//call it:
funcs["sum"](a, b);

You can simply access your function via indexing with the strings

Sign up to request clarification or add additional context in comments.

3 Comments

This worked, I also just found that window[funcName](a, b) is the best solution for this. Thanks for your answer! Definitely something I can use in the future.
oh yeah, this solution is "universal", as it works also in Node.js or backend wise but in a browser you can use the window object, sure
Thanks! Upvoted your answer btw, just won't reflect cause of reputation. I appreciate the shared knowledge good sir.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.