Execution Context in Javascript

Execution Context in Javascript

Each and every browser has their own javascript engine for running the javascript scripts , the most popular ones are v8 engine.

When the javascript engine first starts to read the script it creates a environment called execution context.

There are two types of execution context:

  • Global Execution Context
  • Function Execution Context

Global Execution Context :

  • When the engine first starts reading the script it creates Global Execution Context

Function Execution Context:

  • When the function is called then Function execution context is created

There are two phases in the execution context , They are

  • Creation Phase
  • Execution Phase

Article content
Javascript code snippet

Take a look at the above code snippet to better understand what is happening ,

  1. In the creation phase the js engine allocates memory to all the variables and functions
  2. In the above code , title and message are allocated memory and stored as undefined in the memory
  3. Js engine allocates memory to the post object
  4. And then reference to the function is stored in the current execution context and memory is allocated.

Execution Phase:

  1. The Js engine again starts to read the script from top to bottom
  2. First it logs the post object to the console
  3. The variable message value is logged to the console as undefined , because till now js engine did not assign value to the message variable
  4. The variable title value is logged to the console as undefined , because till now js engine did not assign value to the title variable
  5. The string literal that is assigned to the message will be stored in the memory
  6. The string literal that is assigned to the title will be stored in the memory
  7. It logs the strings that are stored in the memory of variables message and title

Article content
Output of above code snippet

  1. And finally the function calls are made and separate execution context for each function call is created.
  2. In the function execution context also both the phases will be similar.
  3. The same process will be repeated for each and every function call
  4. Those function calls are put on to the stack frame and those function calls will be executed in order.
  5. Take a look at the output to understand what the output will be for each function call.#execution context #javascript #global execution context #function execution context

To view or add a comment, sign in

More articles by B BHARATH

  • What are closures in Javascript ?

    A closure is a combination of a function and references to its surrounding state usually known as lexical environment…

    1 Comment

Others also viewed

Explore content categories