Learn hoisting in JavaScript. The practical way.

Rajesh Bhattarai
2 min readSep 19, 2021

--

Photo by Tim Mossholder on Unsplash

Hoisting in Javascript is the process where the compiler allocates memory for variables and function declarations prior to the execution of code.

Didn’t get it huh? Let’s see the code below.

CODE:
var x = 7;
function greet() {
console.log("Hello");
}
greet();
console.log(x);
OUTPUT:
Hello
7

Yes, I know it was pretty simple to understand code. Now let’s just tweak it a bit.

CODE:
greet();
console.log(x);
var x = 7;
function greet() {
console.log("Hello");
}
OUTPUT:
Hello
undefined

So what just happened? Why did we get var x is undefined?

Actually, the compiler allocated memory to var x before the code is executed. It means before var x is initialized by value 7, the compiler allocated memory to var x with undefined. So yes, now the var x stores something called undefined.

Now, you might be saying wait a minute if the compiler is allocating memory to var x with undefined then when will the value 7 which we initialized to var x be assigned?

Well, that is done once all the variables and functions in your programs are allocated to the memory (it is also called the memory phase). Once the compiler is done with memory allocation then we go to the next phase called the execution phase.

In this execution phase, all the variables are assigned to their respective values. In our case, var x is assigned with a value of 7.

Now in the above example, when we run our code we get console.log(x) as undefined because during the memory phase var x was assigned undefined.

And since we console.log(x) before the statement var x = 7 which resulted in consoling the var x value before it reached the execution phase. And that’s how we got undefined.

So that’s my friend is the classic example of hoisting in javascript.

And now you might be comfortable with the definition of hoisting given at the top.

If you want more such content then do follow me on Twitter LinkedIn and Instagram.

--

--

Rajesh Bhattarai

I am a software developer who loves writing blogs about programming and web development.