JavaScript Execution Contexts and Call Stacks

Tram Ho

JavaScript has become one of the most popular programming languages ​​today. It also leads the way in terms of the number of GitHub repositories and is the most discussed programming language on StackOverflow .

It is therefore very important that you understand the basics and know what happens behind any JS program and how it is executed, if you want to dive into JS.

Execution Context (EC)

Everything in JS happens inside the Execution Context . It is the environment in which the JS code is executed. It includes the value of ‘this’, variables, objects, and funtions that the JS code has access to at any given moment as key-value pairs. Each code block will have its own EC that it is executing.

Take a look at the image above, it consists of two parts

  • Memory: All variables contained in your code are stored here as key-value pairs
  • Code: This is a thread where code is executed, one line at a time

Types of Execution Contexts

  • Global Execution Context (GEC) : It is created once for all programs by default. It includes code that is not inside any function. The GEC is mainly responsible for two things:
    • it creates a global object, the window object (for browsers).
    • it sets the value of this equal to the global object .

    GEC is cleared after the entire execution of the program ends.

  • Function Execution Context (FEC) : Every time a function is called, an execution context will be created for that function. It is cleared when the function returns something or its execution finishes.

How is an Execution Context created

The JavaScript Engine creates the Execution Context in two phases:

  • Creation Phase : At this stage, the JS engine just scans the entire code but doesn’t execute it. It creates a scope chain and then allocates memory for every variable (with its value undefined ) and function in its scope. It then also initializes this .
  • Execution Phase : In this phase, the JS engine performs a re-scan of the code to update the variables and complete the execution.

Whenever you run your JS code, in the Creation Phase , a Global Execution Context is created to store all global variables whose value is undefined and functions with their bodies as values. Then a unique EC is created for the other functions to behave the same way:

  • it first stores and allocates memory for all local variables of that function
  • executes the block of code and self-destructs after its Execution Phase ends.

For example:

With the above code, when executed it will run as follows:

  1. When the above code is run, it will first enter the Creation Phase . All the code is scanned by the JS engine and the Global Execution Context is generated.

  1. In the second scan, when it is in the Execution Phase , each line of code will be scanned from top to bottom and the value of a is updated to 10 – because JavaScript is a synchronous, single threaded language it has to scan line down from top to bottom.
  2. When it scans to the line var result = doubleTheNumber(a) . It will go to this function to scan.

  1. Now, to execute this function, the execution steps will be similar to the steps above. An EC will be created for it. During the creation phase , memory is created for DoubleNumber .

  1. During the execution of this function, since the value of number is 10, the doubledNumber will be 2 * 10, which is 20. It will then return 20

  1. After the return statement, execution context for doubleTheNumber function will be canceled / clear and JS Engine will return to the line var result = doubleTheNumber(a) , where the value of result will be updated to 20.
  2. The last line of code is executed – console.log(result); – Then this program’s Global Execution Context will be canceled / clear.

In the above example, you can understand how a JS Program is executed. However, in reality, its execution will not be as straightforward as steps 1-7 as above. JS Engine uses CALL STACK to manage and execute these steps.

CALL STACK

The Call Stack maintains the order of execution of the Execution Contexts . It is also known by names like Program Stack , Control Stack , Runtime Stack , etc.

It is a stack / stack that includes all ECs. The GEC is always the first EC pushed onto this stack and also the last EC poped out. Whenever a new EC is created, it is pushed onto the stack. When its execution ends or it returns a value, it will pop out and the JS engine moves to the next step on the Call Stack.

For example:

Explain the operation of the call stack:

  • When running the above code, the GEC will be first created and pushed onto the stack. During execution, when JS Engine executes the function doubleTheNumber , a new EC is created specifically for this function and pushed onto the stack. When execution is finished, this EC is retrieved and JS Engite returns to GEC. After the complete execution of this code, this GEC will also be retrieved!

Similarly, you can also physically test how Call Stack for any given JS code. Run your JS code in the browser -> Open console -> Sources. You will Call Stack as shown in the image below:

At this point, the Call Stack will be empty because the code has finished executing. To see the creation and removal of ECs add breakpoints to your code and run it.

Conclusion

Above, we went through how a piece of code is executed in JS, how JS manages the implementation steps. Hope it can help you understand more about JS and understand it better

Reference

Share the news now

Source : Viblo