Execution Context | JavaScript

We are going to learn execution context in javascript with 3W1H, problem-solving techniques.

  1. Why do you need to know the execution context in JS?
  2. What is the execution context?
  3. Where and how it is used?

Why do you need to know the execution context in JavaScript?

  1. You should master this concept before calling yourself intermediate (or even senior) JavaScript developer.
  2. You will get at least knowledge on how the JavaScript engine works. (v8=> Chrome, Chakra => IE, SpiderMonkey => Firefox)
  3. This will help you understand other concepts like hoisting, scope chain, closure, memory allocation, design pattern and framework.
  4. This will help you find new opportunities as a JavaScript developer.

What is the execution context?

It is the wrapper/environment in which the JavaScript codes run.

JavaScript Engine is a program that converts high-level code(instructions) to low-level (machine level code) and is responsible for creating an execution context.

Execution context has 2 phases
- Creation Phase
- Code execution Phase

A. Creation Phase | Execution Context

During this phase,

  1. JavaScript interpreter places all variables and functions in memory space and making them available in code execution phase. All the variables are initially assigned to undefined, which is called HOISTING.
  2. Scope chain (outer environment) is created.
  3. The global object is created and ‘this’ is set in during this phase.

B. Code execution phase | Execution Context

In this phase, 
- the assignment to variables is done.
- the code is executed line by line.

Where and how it is used?

Example:

Creation Phase:

  • str is allocated memory and assigned to undefined.
  • function greet() is dumped as it is in memory.
  • this refers/points to the window object (more reference in coming tutorial)

Code execution Phase:

  • The code is executed, JavaScript engine points to line 1 and variable str is assigned to “Hello World!”
  • Line 3 is executed and greet() function is called as it available in memory and “Hello World!” gets printed in console.

This concept will help you understand other concepts like hoisting, scope, and closures more easily and deeply.