How JS code executed in browser

How JS code executed in browser

Ever wonder about the most beautiful language used for web development, JavaScript, and how it works behind the scenes? and how the code you write is getting executed? If not then don’t worry read this article till the end you will understand everything.

CallSatck

JavaScript is a single-threaded language, so it can do only one thing at a time. Js engine has call stack to manage execution contexts: the Global Execution Context and Function Execution Contexts.

Global Execution Context

Global execution context is created when js code first runs in the browser, it's a simple object also known as Window.

So Global execution context consists of two phases, the First phase is Memory allocation and the second phase is code execution, In the first phase memory is allocated to each line of code and in the second phase, the code is executed line by line. Yes, memory allocation happens before code execution that’s why concepts like hoisting exist.

Behavior of variables

Let’s understand the behavior of the variable which will clear your doubt about hoisting.

when you declare any variable the value of the variable is stored as an undefined in 1st phase so when you try to access the variable before it is executed then it will return the value i.e undefined.

but in the code execution phase the value of the variable will be allocated properly, So if you try to access the code after code execution then the variable return the undefined value.

var a = undefined // 1st phase

var a = 2 // 2nd phase

Also with these 2 phases, the GEC also have a local memory group of web APIs that browser provide’s to us, which we can access by using the window object also with this(remember the value of this is depends on where it is called) these web APIs are so useful that we use them to fetch data from the server, consoling the output, using timers like setTimout, setInterval, etc.

Now let's discuss how Javascript and browser together execute the code. So when you write any line of code the GEC is created inside the callstack, callstack is like a box that manages the function invocation and heavy work of JS. for now just remember whatever comes inside callstack will get executed instantly.

Function Invocation

Now when any function is invoked the new Execution Context is created inside the callstack. which also has the same 2 phases as we discussed earlier. These all functions and their execution contexts has independent local memory and lexical environment. For now, consider lexical environment as a local memory and the lexical environment of its parents. so you will think this is so much work right? Yes but call stack handles it so beautifully that we don't even realize and make a fraction of milliseconds task.