Process that calls itself (A function that calls itself)
Note: When JavaScript sees the return keyboard, the compiler will remove.
Inoke the same function with a different input until you reach base case.
The condition when the recursion ends.
if(num === 1) return 1;
Loops the numbers 3.. 2... 1.. then 0 which outputs 'Done'
function countDown(num) {
if(num <= 0) {
console.log('Done')
return;
}
num--;
countDown(num)
}
countDown(5)
countDown(3) print 3... countDown(2) print 2... countDown(1) print 1...
Then it finally reaches countDown(0) which is the base case.
num === 1 return 1;
function sumRange(num) {
if (num === 1) return 1;
return num + factorial(num - 1);
}
sumRange(5) // 120 ( 5 * 4 * 3 * 2 1 )
factorial(3)
return 3 + sumRange(2)
return 2 + sumRange(1)
return 1
(Backwards)
return 1; sumRange(1) === 1
return 2 + 1 2 + sumRange(1) which is 1 so 2 + 1
return 3 + 3 ; 3 + sumRange(2) which is 3 (2 + 1)
so the final output is 6