Understanding Hoisting in JavaScript

Abdullah Imran
The Startup
Published in
3 min readAug 19, 2020

--

In JavaScript, Hoisting is the default behavior where variables and function declarations are moved to the top of their scope before code execution.

No Matter where function and variable are declared, it moved up top on their own scope. Doing this, it allows us to call functions before even writing them in our code.

How interpreter sees the above code:

We Know, In JavaScript, when we have a variable that is not defined then it occurs an undefined error. So in the above example, JavaScript only hoists the declarations part and we got an undefined error.

It’s important to keep in mind that, JavaScript only hoists declarations, not the initializations.

let us take another example,

why this time we got a ReferenceError? Because of trying to access a previously undeclared variable And remember JavaScript only hoists declarations. So Initialisation can’t be hoisted and we got an error.

ES6: Let Keyword

Like before, for the var keyword, we expect the output to be undefined. But this time we got a reference error. That Means let and const variables not hoisted? The answer is Variables declared with let are still hoisted, but not initialized, inside their nearest enclosing block. If we try to access it before initializing will throw ReferenceError due being into Temporal Dead Zone.

Hoisting functions

Like variables, the JavaScript engine also hoists the function declarations. And it allows us to call functions before even writing them in our code.

Hoisting in function expressions are not allowed at all. If you doing this you will get an error.

I hope this lesson provides a clear understands of how Hoisting works in JavaScript. Hopefully, you learned something today. Happy Coding.

--

--