How does JavaScript language work internally?

Bharath Uday
2 min readMay 10, 2021

--

When a web browser encounters a JavaScript program it uses a combination of Stack Data Structure,Queue Data Structure and Web API Library to achieve the desired outcome.Outside of a browser the run time environment for JavaScript is provided by a V8 engine(Sounds like an automobile part right?).

Let us look at this a little more in detail.

Let us assume that we are going to execute the following program:

Sample Code

Every line of code in this program is pushed into a Stack by the Compiler as it reads the JS file top to bottom.The first entry into the Stack will be the main() function or the parent function of the program you are executing followed by the contents of the JS file one at a time.Once the code enters the stack if it contains any Web API specific code like timeout functions, AJAX api calls etc it will be moved into the Web API Layer inside the compiler.

JS Execution Cycle

The code continues execution on the main() thread within the Stack while all the asynchronous operations are executed separately.Once the asynchronous operation completes its execution it is enqueued into an Event Queue.The “Event Loop” which is responsible for dequeueing the contents of Event Queue onto the call Stack waits for the Stack to be empty.Once it’s empty, the Event Loop dequeues all the Queue contents onto the Stack in a First In First Out Order(FIFO).With the introduction on ES6 & promises, the promise that originates from an AJAX call will be handled separately inside a JOB Queue and not within the Message Queue & Web Api Layer.

--

--