Checkout my twitter thread explaining how functions work in memory (stack).
Things to keep in mind to understand functions behavior
- When a function is called, it gets in the stack, and stays there until its execution.
- When the function completes executions, it gets off the stack and returns to the program flow.
- When the function is called, it is loaded on the stack with its arguments.
- When it completes execution, it gets off the stack and the program returns to its previous program flow.
If "A" function calls "B" function, "A" function will remain in the stack (and in scope also) until the "B" function returns. It means that not only the currently executing function remains in the function but also all the parent function that called it.