How JavaScript code Work.

How JavaScript code Work.

As , We developer already know that JavaScript is single threaded single concurrent language (it handle one handle one task at a time)

so whenever we run any code in JavaScript , few backend process happen that makes our code working .

JavaScript has a single call stack which along with others parts like heap , queue , event loop makes our code run smoothly .

Call Stack : its a data structure which records functions calls ,whenever we call a function to execute , we push function into stack and after function call done its pops from queue.

All things happen in Execution Context , it is a place where JS code evaluated and executed.

Global Execution: This is a default or base execution context .The Code that is not inside any function is called Global execution. it created global object which is window and set value this to equal global object. There is only one global execution.

Function Execution : When ever function invoked , a brand new execution context created for the function . Each Function has its own execution context. Execution is all about lexical environment of value and function.

How async function works in Call Stack?

Suppose , there is a async function like setTimeout(), set Interval(), promises.

When user waiting for response of a async function to complete and there associated callback called. Browser API kicks in and call its API which are basically threads created by browser in c++ to handle async DOM events ,HTTPs requests , set Timeout then Web API pushes callback onto queue when its executing

to move thread from queue to call stack, event loops is responsible execution of these call back in queue and pushing in the stack.

Event Loop job is look in queue and stack and put in stack when its empty or free.

Event Loop : All application code that is inside callback function not top top level is responsibility of event loop.