Evening, novice here, i've been trying to use tail recursion using the Function object but when i call the function again in it's body and evaluate it, it returns an error signaling that it hasn't been defined. I want to know if it's posssible to use the Function object recursively because i want to makek a function with it that takes any amount of argument, and the only way i can think of to solve it, is using recursion
var sum = new Function('...args',
'if(args.length==2) return args[0] + args[1]; else return args[0] + sum(...args.slice[1]);');
/*
-console.log(sum(1, 2));
->returns: 3
-console.log(sum(1, 2, 3));
->returns: Error: sum is not defined
*/
I made the same function the regular way and it worked like i expected:
function sum2(...args){
if(args.length==2) return args[0] + args[1];
else return args[0] + sum2(...args.slice(1));
}
/*
-console.log(sum2(1, 2));
->returns: 3
-console.log(sum2(1, 2, 3));
->returns: 6
*/
Function, you get the code in global scope, sosumis likely not there. Also, this seems like an XY problem - why do you need a dynamically evaluated function body with tail recursion?