Recursion is when a function calls itself and the function that does is called a recursive function.
You have to be careful writing the recursive function because if it can overflows the stack calling itself again and again.
Just like this factorial recursive function
function factorial(a) {
if (a == 0) {
return 1;
} else {
return a * factorial(a-1);
}
}
console.log(factorial(10));
//3628800
Or like this power recursive function
function power(a,b) {
if (b == 0) {
return 1;
} else {
return a * power(a,b-1);
}
}
console.log(power(2,4));
//16
Both of those functions above call themselves multiple times till they meet the return condition.
Performance wise, calling a function itself is not always effective since its slower than the regular looping function. It’s completely up to the programmer what they want to go with.
If you’re in a dilemma of choosing between the regular loop or a recursive function, I would suggest to test out both ways before going live and compare the performance.
If the program is not big enough then you might find the recursive choice better depending on your program logic.
examples factorial functions power recursion