Hoisting in JavaScript

Hoisting in JavaScript

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

Hoisting is a JavaScript mechanism 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 can be moved up top on their own scope. Doing this, it allows us to call functions before even writing them in our code.

image1.png

How interpreter sees the above code:

image2.png

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.png

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.png

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.

image.png

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

image.png

Note:

A class should be defined before using it. Unlike functions and other JavaScript declarations, the class is not hoisted.

For example,

// accessing class
const p = new Person(); // ReferenceError

// defining class
class Person {
  constructor(name) {
    this.name = name;
  }
}

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