Javascript Execution Context and Call Stack

Javascript - Synchronous callstack

To become a javascript or web developer we must know how javascript works internally. By understanding this you will get to know how to write non-blocking code.

The Javascript Engine

It is an engine that executes your javascript programs or code. the most popular javascript engine is V8.

javascript engine

v8 Engine

The google v8 engine internally works with chrome. It has two-component as below-

  • Memory Heap
  • Call Stack

Memory Heap: It is unstructured memory used for memory allocation to variables and objects.

Call Stack: LIFO, it is a data structure used for function calls and records where we are in the program. We know that javascript is a single-threaded programming language that means it runs one thing at a time and has a single call stack.
If we call function, it pushed into the stack at the top and returns function and popped or removed from the top of the stack.

Let's see the below example :

Here, call stack manages execution context as a global execution context and function execution context.

When javascript code run, engine places execution context in the call stack.

The global context moves to the execution phase.

Javascript excecutes the call to average(50,100) function and create function excetion context for the average() function and push it into top of the stack.

Javascript started average function execution and it is on the top of stack.

Insside Average function javascript got addition function so here new execetion context will get create on the top for addition().

JavaScript engine executes the addition() function and pops it off the call stack.

Now Average fucntion is at the top, javascript execute it and pop it from stack.

Now stack is empty and it stops the execution.

Stack Overflow

This happens when we reach maximum limit of stack and this can appears in recursion scenario, Take look below code

When we exceutes above code it will go in infinite stack will be overflow here.

So it takes lots of time to executes and to overcome this javascript added promises,aync/wait i.e. asynchronous callback.

Thank you for reading and feel free add comments👋🏽
Hope this helps you.✌️

Love Programming and Writing, Software Engineer, Pune