javascript create function dynamically code example

Example: how to create a dynamic function in javascript

// for async
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
// assume someAsyncCall is a call to another async func we await for that returns 1 (just make this simpler)
const func = new AsyncFunction('arg1', 'arg2', 'return arg1 * arg2 * await someAsyncCall();');
// now use the function, assuming we are in an async function for the following to work
await func(2,2); // => 4


// for normal non-async functions it's simpler just use the Function constructor
const func = new Function('arg1', 'arg2', 'return arg1 * arg2;');
// now use the function
func(2,2); // => 4