How JavaScript Work? & execution context
Everything in JavaScript happens inside an Execution Context
How this execution context actually looks like
Execution context is like a big box and it has two components in it.
1. Memory : all variables and functions are stored as key-value pairs. ( key: variable ). this memory component is also known as variable environment.
2. code component : code is executed one line at a time. this is also known as thread of execution.
JavaScript is a synchronous single-threaded language
What is single threaded? means JavaScript can only execute one command at a time.
Synchronous single threaded that means JS can only execute one command at a time in specific order. in simple way it can go to the next line once the current line has been finished executing.
How Js code is run?
When JavaScript code run Global Execution context is also created. it has two component memory and code component. so in this example.
The first phase is called Memory Creation phase and another is Code Execution Phase.var x = 10;var y = 20;function ans(){var ans = x + y;return ans}ans();
The Second Phase is the code execution phase. so js engine run whole this code again line by line and execute it. this time actual value of variable placed inside memory component. means it replace undefined to its actual value of x and y.
Inside it execution context create a memory and code component. then again two phases create first is Memory creation and code execution phase.
- In first phase they allocate memory to new variables, parameters and functions. so it store ans then? yes. it store undefined over here. (ans : undefined )
- Second Phase start means code execution will start we will be executing each line and it replace undefined to actual value and other execution is do. means x + y it calculate and return. ( ans : 30).
- if whole code is execute then this execution context will deleted in the call stack.
- Call Stack is a tube like structure. When JavaScript code run Global Execution context will created. it goes to call stack then execute.
- Call Stack follow LIFO (last in first out ) principle means, when global execution context will create it goes to the bottom of the call Stack and execution will finish the execution context popped to the call stack. and call stack is empty.
- Ex
- Call Stacks
- Execution context stack
- Program stack
- Control Stack
- Runtime stack
- Machine Stack
Post a Comment