What is Hoisting and Execution Context?

As a beginner, while learning javascript you will come across terms like closures, this keyword, scope, etc. All these concepts require you to have an understanding of what is Execution context and hoisting. We will understand that in this blog.

  1. Execution Context :-

    Everything in javascript happens inside the Execution Context.

image.png

Let's understand the above code snippet step-wise:-

var a = 2;
var b = 4;

var sum = a + b;

console.log(sum);

Execution context has two components:

  1. Memory Component :

    The memory component is also known as the Variable Environment. This is the place where variables and functions are stored as Key : Value pair. It is important to notice that functions are also stored as key-value pairs where the function name is key and the whole function body is treated as a value.

  2. Code Component :
    Code Component is also known as Thread of Execution. This is the place where code is executed one line at a time. As it is able to execute only one line at a time and it cannot go to the next line until it has executed the current line that's why javascript is a synchronous language.

image.png

  1. Hoisting


printMsg();
function printMsg(){
console.log("let us understand hoisting " );
}
console.log(x);
var x=7;

when you observe the code you will notice two strange things:

  • We are calling the function even before it is initialized(not to be confused with defined)

  • We are accessing the variable x before initializing

So you would naturally expect the program to throw an error, but the output of the above program is this :

output

Now we need to understand two things:

  • Why did calling printMsg() did not throw any error?

    The reason we did not get an error here is because of the two components explained in the execution context. The function is already stored in the memory component when it is called in the code execution phase. So as the function is already stored we can execute it

  • What is undefined and why do we get undefined?

    The thing to notice here is that undefined is a special keyword in js which is assigned to the variables which are not initialized. So in first phase javascript knows that there is variable x but it does not know it's value. so javascript stores undefined as the placeholder for the time being. Until it comes across it's initialization. As we are accessing x before initialization that is why we are getting undefined.

So this whole phenomenon of accessing variables and functions before initialization is called hoisting.

If you want to understand javascript in details please watch the amazing Namaste Javascript series by Akshay Saini