a - What is call stack call stack is a stack-based data structure that holds information about active function calls in a program. Each entry on the call stack is called a stack frame or activation record which contain details such as: 1. The function being executed 2. The current instruction pointer (which line of code is currently executing) 3. Local variables and their values within the function 4. Parameters passed to the function How it works: 1. Function Invocation → When a function is called in JavaScript, its stack frame is pushed onto the call stack. 2. Execution → The function executes, and if it calls another function, that new function's stack frame is added on top of the current one. 3. Completion → Once a function completes execution (either by returning or encountering an error), its stack frame is popped off the call stack, and control returns to the previous function. If the call stack grows too large (e.g., due to deep recursion without a base case or infinite loops), it can lead to a stack overflow error. This happens when there's no more memory available on the stack to push new frames.
b - call stack example Initial State → The call stack is empty. calculate() Invoked → calculate's stack frame is pushed onto the stack. add(3, 4) Invoked → Inside calculate, add is called, so add's stack frame is pushed on top of calculate's frame. add Executes and Returns → add completes execution, returning the value 7. Its stack frame is popped off the stack. calculate Continues → Control returns to calculate, which now has the result from add. It logs the result and then its stack frame is popped off. Visual Representation