Execution context consists of 2 parts:
Thread of execution: Goes through the code line by line and executes it line by line.
Memory: Save data (variables) and code (function) for use.
The call stack helps keep track of which
execution context we’re in – that is, which function is being executed. And help us determine after completing that function, where to return to continue execution. It works according to LIFO (last in first out) mechanism.
Our program is as follows:
When we run the above code, a global execution context will be created with global memory , call stack now we are in
Next, the thread of execution goes through each line of code and executes the following in turn:
Dòng code 1: We declare a constant
numin global memory and assign its value
Dòng code 3: We declare function
multiplyBy2in global memory.
Dòng code 8: We declare a constant
outputand its value is unknown now, why? Since the right side of it is
multiplyBy2(num), we solve it by calling the function
multiplyBy2and passing the argument
multiplyBy2(3) to the call stack.
Overview right now:
We are now in the function execution context of
multiplyBy2(3) , and the thread of execution continues:
- The first thing it assigns a value to the
- It then executes the first line of function
multiplyBy2which declares a constant
resultand assigns its value
inputNumber * 2:
- Next with the line of code
- Get that value return for constant
outputin global memory .
So that has completed
dòng code thứ 8 , the function execution context above will be cleared, the call stack will now take
multiplyBy2(3) off the stack and back to
- Continue execution
Dòng code 9:
const newOutput = multiplyBy2(10);, similarly when executing
dòng code 8:
multiplyBy2(10)will be pushed to the call stack
- A corresponding function execution context is created
- Execute line by line, and return the calculated value to
newOutputin global memory
Overview right now:
So having completed
dòng code thứ 9 , the function execution context above will be cleared, the call stack will now push
multiplyBy2(10) off the stack and back into
Since the program is completed, the global execution context will also be cleared.
So we’ve learned together how execution context and call stack work. In the next article we will learn about Closure .