Skip to main content

Command Palette

Search for a command to run...

Understanding Execution Context in JS

Updated
2 min read
Understanding Execution Context  in JS
B

BSc CSIT Graduate

You are here means you must have written some code in JavaScript and have seen your code do magic-like things. But have you ever wondered what happens behind the scenes when your code runs?
Let's try to get it.

What is the Execution Context?

JavaScript first prepares the workspace/container/environment that holds all the information needed for JavaScript to run the piece of code. That environment is called the execution context.

  • Global context: It is the default context when code runs outside any functions. Or we can say the global code runs in this execution context.

  • Local Execution Context: Every time a function is called, a new execution context (local execution context) is created and pushed onto the call stack. It has its own memory location for the variable and the functions declared inside the function. This context is removed after the execution of the function

Execution Context Phases

1. Memory Phase

setting up your tools on a desk

This is the first phase where JavaScript sets up the environment for your code before actually running it. The memory phase is also known as the creation phase.

JavaScript scans all code before executing it. All variables are loaded into memory with the value "undefined," and functions are stored with their full definitions(fully hoisted).

In the above example, the name variable is loaded in the memory with the value "undefined". And the greet function is loaded with the full definition. This is why we can access the function before its declaration. This concept is called hoisting in JavaScript.

2. Code Execution Phase

actually using the tools to do the work

Now JavaScript starts running your code line by line. This is where values are assigned, expressions are evaluated, and functions are called.

What happens here:

  • Variables get their assigned values.

  • Function calls create new local execution contexts, which are pushed onto the call stack.

  • Code executes in order.

Let's see the table for how the code in the above figure works.

JavaScript first prepares memory and then executes code. Understanding these two phases makes it easier to follow how your code runs.

Now that you know this, you’re ready to dive deeper into JavaScript!

Read more about hoisting in this blog : scope and hoisting in js