Recursive Functions
Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself. In other word Recursive functions are functions that call themselves.
for example see function below
function countDwon(n){
console.log(n)
if(n > 1){
countDwon(n -1) // recursive call
}
else {
return true // base case
}
}
you can see that the function is calling itself and has a condition to stop which we call base case. If there is not stopping condition, function will run forever.
How computers execute a recursive functions:
let say we have a function that sum to number 5.
function sumUpTo(n){
if(n > 1){
sumUpTo(n - 1) + n
} else {
return 1
}
}
sumUpTo(5)
// this translates to
sumUpTo(4) + 5
// then
sumUpTo(3) + 4
sumUpTo(2) + 3
sumUpTo(1) + 2
// 1
to explain the code above: JavaScript is breaking down our function. What is the sumUpTo(5)? Well it’s the sumUpTo(4) + 5. What is the sumUpTo(4)? It’s the sumUpTo(3) + 4. All of these sumUpTo are unsolved puzzles for JavaScript until we get to sumUpTo(1). Our function says that sumUpTo(1) returns 1 (by virtue of the else
block).
In order to create a recursive function, the first step is to set a conditional statement that tells the function when to stop calling itself. Next, create an argument that will execute and call itself at least once.