DEV Community

Cover image for  Javascript behind the scenes!
Mandeep Singhmar
Mandeep Singhmar

Posted on • Edited on

Javascript behind the scenes!

Execution context(EC)

Everything in javascript happens inside the environment called 'execution context' where the javascript code executed.

So, javascript code runs in two phases in this environment.

The first phase is memory phase or creation, in which the memory is allocated to all variables and functions from top to bottom. Variables value stored equal to undefined and in the case of 'function' the whole function stored in memory phase.

The second phase is execution phase, in which code will execute line by line, bcz as you know javascript is a synchronous or single threaded language.

This global execution context or execution context will be deleted after the execution of whole code.

Their is one more thing to remember function execution context, when we envoke a function the function execution context is being created inside
gloabl execution context for every function.

The function execution phase has access to a special value called arguments.

Hoisting

Let's take a look at hoisting, once you got the hack of how execution of javascript works then it's going to be easy.

so, hoisting is a phenomena in javascript by which we can acccess variable and function even before we have initialize it.

You, will think that how it's possible that, how we can access variables or functions before their initialization.

Let's take a look at this example:

getFruit();
console.log(name);

var name = mandeep;

function getFruit() {
  console.log('Mango')
 getCar();
}
function getCar() {
  console.log('Lambo')
}



// so, we will get these values, even before initialized the variable and function.

//undefined
// Mango
//Lambo
Enter fullscreen mode Exit fullscreen mode

Do, you know all of this happend bcz of execution context.

In the creation phase,

The memory gets allocated for the variable name, and a special value undefined is assigned to the variable.
In the execution phase,

The console.log(name) statement will execute.
This mechanism of allocating memory for variables and initializing with the value undefined at the execution context's creation phase is called Variable Hoisting.

So, now let's talk about Function Hoisting. It follows the same pattern as Variable Hoisting.

The execution context creates the memory for the function and puts the entire function declaration of getFruit function in it in memory phase.

The functions create their own execution context. So a similar thing happens for function getCar as well.

Next, the functions get executed in their execution context respectively.

Putting the entire function declaration ahead into the memory at the creation phase is called Function Hoisting.

So, this was the brief overview about execution context and hoisting in javascript. Hope you liked it and understand it.

Top comments (0)