A quick look at how code is executed in JavaScript.

·

3 min read

For a piece of JavaScript code to be executed, it has to go through multiple processes behind the scenes. Let's try to understand more about it using an example.

Here is what our example will look like: Twitter post - 13.png

Before we explore the example, let's see what an Execution context is.

The Execution context is an environment where the javascript engine executes our code.

It has two main components:

1. Memory Component (Variable environment)
2. Code Component (Thread of execution)

Memory Component

Variables and functions are assigned memory space, and the data associated is stored as a key-value pair.

Code Component

After the memory is assigned, the JavaScript engine starts executing code inside our execution context one line at a time. Twitter post - 13.png

From the picture above we can see that there are two types of execution contexts that are created.

1. Global Execution Context
2. Local Execution Context

Global Execution Context (GEC)

When the JavaScript engine begins executing our code, it creates a global execution context (GEC).

GEC is the default execution context, where all JS code that is not inside a function gets executed.

‼️ Every JS program has only one GEC ‼️

Function execution context (FEC)

When we call a function, the JS engine creates a new execution context called the Function execution context inside the GEC.

We again go through the memory creation & code execution phase but for the variables and functions inside our FEC.

Now that we understand how the execution context works, it's time to see it in action with the help of code.

The arrow on the right indicates the line at which the JavaScript engine is.

It mimics the behavior of the JavaScript engine.

Here is how code execution occurs:

  1. Javascript engine evaluates our code.
  2. It enters the Memory component (memory assignment phase).
  3. Assigns memory to all variables and functions in our code and set's a default value of undefined.
  4. Upon memory assignment, it enters Code Component (code execution phase).
  5. JS engine executes our code one line at a time, then assigns value to the desired variable.
  6. On encountering a function, it creates a new Function execution environment.
  7. Assigns memory to all the local variables and functions and executes the code inside the function one line at a time.
  8. When the JS engine completes function execution, it removes it from the execution context, and memory is garbage collected.
  9. And finally, when everything in the global execution context is executed, GEC is removed from the execution context, and the memory is garbage collected.

Thank you for hanging along so far. If I added value to your time, I would love to hear your thoughts on the article.