Javascript is a scripting language that runs inside an environment which is called a javascript run time environment like any browser or node js.
initially, javascript was used for only the client side to update content, and manage multimedia but after introducing node js we can use it as a server-side language.
How it works
Execution Context
All code of javascript runs inside a wrapper which is called Execution Context. Execution context provides the following things
Global Object - for the browser it's a window object.
This - it is calculated for the browser it's equal to the window object.
Thread Of Execution - Here memory allocates to variable and function statement.
The code that is not inside any function is called the global area and the wrapper that is created is called the global execution context.
Execution context created before execution of code.
Memory allocation for the variables and a function statement is done before executing the code this is also known as hoisting.
In javascript code runs top to bottom.
Function statement allocated memory inside the heap.
variables are assigned with undefined.
Variable declare only one time in the execution context.
Call Stack
Execution Contexts are present inside a stack which is called Call Stack.
As any function will be called new Execution context is created inside the call stack and removed as the function code gets executed.
Example
function real() {
console.log('I am real function');
}
function real() {
console.log('Second one is real function');
}
function real() {
console.log('Third one is real function');
}
real() // output: Third one is real function
Let's see how the execution context works for this
Above at first GEC(Global Execution Context) will be created and for every real function memory allocated inside the heap but inside the GEC real will refer to 16K regardless of where the function gets called as the real function gets called new execution context is created but there is no memory allocation will be done becuase no varaiable and function inside available so it will print "Third one is real function".