Global Execution Context? what it is & how it created
- This is the 4th Blog,
- Today, I will discuss how Global execution context formed in the bottom of the Call stack when we run any JS program. JavaScript is the only language which understood by the all the browsers. Each browsers has its own JavaScript engine, which interprets the code.
for example:
- v8 -> Google Chrome
- Spidermonkey -> Mozilla Firefox
- JavaScriptCore -> Apple safari
- Chakra -> Microsoft Edge
Each browsers follow EMCA standards, But some may differ for anything which is not defined by the standards
Now lets deep dive Into the browser, Where I asked Who are you JS?
JS say :-> I am synchronous single threaded language, I can do one thing at a time. I have single call stack, event queue, callback queue and some other web API which is provided by the environment like browsers and NodeJS.
Then I asked to v8, who are bro?
v8 says -> I am runtime inside the chrome and I only have call stack and heap. Heap where memory allocation happens and Callstack is a data structure, which records basically where in the program we are. Intresting thing about v8 is that→ when you clone the v8 codebase and grep the things like setTimeout, DOM manipulation, AJAX,network request. it is something which is not there. how intresting!!! because it is first thing we use, when we think about async stuff and it is not there in v8 source code. This Aync stuff web API provided by the browser.
How JS runs?
Everything happens in Global Execution Context(GEC), Remember when we run program of JS, A GEC is created in the Callstack and it has two component one is memory component(variable environment) and another one is Code execution component.
After Creation GEC, it run in two phase
Memory creation -> In this phase, all the variables and function of the program gets stored in the memory component as key: value pairs. and value of all the variable sets to undefined till the code execution. This is known as Hoisting
code Execution -> In this phase, code starts executing step by step in the code execution component synchronously.
If we step into function, we put something in the stack and if we return from the function we pop-of from the top of the stack. That's how JS runs in Callstack.
Async stuff, AJAX, network request terms like this, I will going to discuss this in upcoming articles.
Thanx for reading this
- Happy coding :)