call stack
-
Any time a function is invoked it's placed(pushed) on the top of the call stack.
-
When seeing the
returnkeyword or when the function ends, the compiler will remove(pop)
When we write recursive functions, we keep pushing new functions onto the call stack!
How recursive functions work
Invoke the same function with a different input until you reach your base case.
base case: The condition when the recursion ends.
SO, 2 essential parts of a recursive function:
- Base Case
- Different Input
Basic recursive function
const sumRange = num => {
if (num === 1) {
return 1
}
return num + sumRange(num - 1)
}
console.log('--------')
console.log(sumRange(10))
console.log(sumRange(5))
console.log('--------')