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.

Image for post

How interpreter sees the above code:

Image for post

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,

Image for post

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

Image for post

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.

#javascript-hoisting #understanding #js-hoisting #javascript #hoisting

Understanding Hoisting in JavaScript
1.65 GEEK