let add = new Function("num1", "num2", "return num1 + num2");
Thanks to added ES6 functionality, you can also include default parameters to your dynamic function as such:
let add = new Function("num1", "num2 = 0", "return num1 + num2");
In this case leaving out the second argument would simply default it to the value of 0 to prevent any Nan scenario.
Using rest parameters
Again, thanks to ES6, you can also use the rest operator as the first argument as follows if you are unsure of the number of arguments, or if they vary in number from function call to function call:
let getCount = new Function("...args", "return args.length");
console.log(getCount(1, 2, 3)); // returns 3
You could also potentially have incredibly dynamic logic that changes based on multiple variables and/or parameters and require this flexibility.
I think in the future we'll definitely be seeing much more of this procedure as technology and coding techniques advance in nature. For now, if you have any unique use cases for dynamic function creation, comment down below.
Did you find this article helpful / fun / useful?
Sign up for my weekly coding tips!
* I never share and/or sell your email folks!