“ Let us understand recursion ”
Recursion is a process in which we define a step or a process and let the code do the rest steps by this we achieve the same result with less coding
Recursion is a process of calling itself
To put an end to the process we must define the base case
So what is the base case? let's understand that with an example
function print(num){ if (num <= 0){ // this is the base case
return 0
}
console.log(num) print(--num) // this step is recurrsion }print(4)/*output4
3
2
1*/
Now to the point what if we don't mention the base case or provide a proper base case, In such we get a stack overflow error
This is because the function will go on calling itself all these function calls will be put on to the stack when the stack is full and we dint get a base case the result will not be returned so we get a stack overflow error
Find the factorial of a number using recursion
function fact(num){ if (num == 0){ // base case
return 1
}
let ans = num * fact(num-1) // recurrsion return ans}console.log(fact(5))