The Execution Context
When `factorial(3)` calls `factorial(2)`, the computer cannot just overwrite the `n=3` variable. It creates a brand new "Execution Context" and pushes it to the top of the Call Stack.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Every time a function calls itself, the computer uses a hidden data structure called the "Call Stack" to remember where it left off.
When `factorial(3)` calls `factorial(2)`, the computer cannot just overwrite the `n=3` variable. It creates a brand new "Execution Context" and pushes it to the top of the Call Stack.
The last function called (`factorial(1)`) is the first function to finish. As it returns, its context is popped off the stack, and the function beneath it resumes exactly where it paused.
If you forget the Base Case, the recursion will never stop. The Call Stack will grow infinitely until it exceeds the memory allocated by the OS, causing a crash known as a "Stack Overflow".