Javascript

Execution Context and Call Stack in JavaScript

Execution Context in JavaScript

Everything in JavaScript happens inside an execution context.

Execution context have  two components:

Variable Environment or Memory Component  – Stores Key value pairs

Thread of Execution or Code Component      –  Code gets executed one line at a time.

JavaScript is synchronous single-threaded programming language.

Three types of execution context:

Global Execution Context

Functional Execution Context

Eval Function Execution Context

How JavaScript Code is Executed

The JavaScript engine creates the global execution context before it starts to execute any code.

A new execution context gets created every time a function is executed, as the engine parses through your code.

When a new execution context is created on a function call, first step memory creation phase.

After memory creation phase, step by step execution of code takes place.

JavaScript Execution Stack LIFO (Last in, First out)

The JavaScript engine can only be executing within a single context.

So how does it manages all this?

When the JavaScript engine first encounters your script, it creates a global execution context and pushes it to the current execution stack.

Whenever the engine finds a function invocation, it creates a new execution context for that function and pushes it to the top of the stack.

The engine executes the function whose execution context is at the top of the stack.

When this function completes, its execution stack is popped off from the stack, and the control reaches to the context below it in the current stack.

Please check below the video for detailed explaination along with line by line code execution demo:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s