JavaScript Hoisting

Hoisting in JavaScript is a mechanism where all variables and functions move up on initialization phase. Before getting about hoisting let’s see an example.

Most of the time when show this code snippet and ask what would be the output most of say it is “10” and they might explain in JavaScript all the globally declared variables moves up before the execution phase which means in initialization phase. But the answer is not “10” it print as “undefined”

In JavaScript initialization phase all the variables and function moves up but it only moves variable declaration but not the variable values. so above example it moves variable declaration up but not the value.

This is how actually the above code looks like in initialization phase which means the variable declaration moves up but not the value since we accessing that value before initialization it shows “undefined”.

Then what about the output of this given code does it print undefined. This code does not give output this give an Error.

“ReferenceError: Cannot access ‘a’ before initialization”

So now you know this code is not working does that mean JavaScript hoisting is not working with “let” and “const” variables before that lets see another code.

What does this code does in this we are just access variable call “a” which is not even exists so this give an error .

“ReferenceError: a is not defined”.

So when we try to access “let” and “const” variable before declaration it gives us cannot access before initialization. which means JavaScript knows there is a variable exist when we create variables with “let” and “const” but it does not give us chance to access those before initializing it.

Most think hoisting only work with “var” not with “let” or “const” but actually hoisting work with both “let” and “const” if it does not happen it should give and error like “variable is not defined” but it does not give that means hoisting worked with “let” and “const” but only problem is JavaScript does not allow to access those until we initialize those variables.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store