Hoisting In JavaScript
Tags: webdev, javascript, hoisting, discuss
Published: 2022-06-12 06:59:00

> _This blog is originally published on my Blog website, where you can find the full version with detailed insights and examples. Click the link below to read the complete article and explore more tech-related content!_
> 👉 [Click Here](https://devwebbytes.blogspot.com/2023/07/javascript-hoisting-explained-key.html)

Hello DEV community I gonna discuss the Hoisting in JavaScript in every aspect such as how Hoisting works with functions, variables (var, let, and const), and classes. 

## Table Of Contents
        

1. [Introduction](#Introduction)
2. [Hoisting Function Scope Variable: var](#variable-var) 
3. [Hoisting Scope Variable: let](#variable-let) 
4. [Hoisting Constant: const](#variable-const) 
5. [Hoisting Functions](#variable-function) 
6. [Hoisting Classes](#variable-class) 
7. [Conclusion](#conclusion) 

      

### Introduction  <a name="Introduction"></a>
Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution.
It gives us an advantage that: 

- No matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
- It allows us to call functions before even writing them in our code. 

**Variable Life Cycle:** `Declaration –> Initialization/Assignment –> Usage` 

![Variable lifecycle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/za1qo3hcbgg0l4irm6fp.png)

JavaScript allows us to both declare and initialize our variables simultaneously, this is the most used pattern:  

![example2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i07iw2adsncealx1dog9.png)



**Note:** Always remember that in the background the JavaScript is first declaring the variable and then initializing them.

in JavaScript, undeclared variables do not exist until the code assigning them is executed. Therefore, assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. This means that all undeclared variables are global variables.

![hoisting example2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/phg8bxcxkfx53b7b0a93.png)


**Function Life Cycle:** `Declaration –> Usage `
In the case of Function, a function can be declared and later used (or invoked) in the application. The initialization is omitted. For instance:

![Function Life Cycle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/skom6cujx4lnhsg33qp2.png)


### Hoisting Function Scope Variable: var <a name="variable-var"></a>
Hoisting with var is somewhat different as when compared to let/const. Let’s make use of var and see how hoisting works:  


![global scope](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c8cd0te15jiza9kztvpq.png)


The above code interpreter sees differently:

![global scope 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmlfdjcfhcrmn0wtekne.png)

Hoisting with var work same in function scoped variable as it shows above.



### Hoisting Block Scope Variable: var <a name="variable-let"></a>
Tell now all we discussed is about general hoisting which is 100% applicable on functions and var type variables as defined because let and const types variables cannot access/use able before declaration.

But hoisting work mechanism is different for let types variables.
As if we try to access the let variable before declaring it causes a ReferenceError that the <variable_name> is not defined.


![Hoisting Block Scope Variable 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jw9nkx5y2pvd5nufc7na.png)


By default a declared yet not initialized variable has an undefined value. 


![Hoisting Block Scope Variable ex.2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47rkelb0exi4ok90do4y.png)


### Hoisting Constant: const <a name="variable-const"></a>
The constant statement creates and initializes constants inside the block scope:

![Hoisting Constant ex.1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fzhk6y2igt3a1j7nzqmv.png)

When a constant is defined, it must be initialized with a value in the same const statement if this rule does not follow the error `SyntaxError: Missing initializer in const declaration` will be thrown. 
After declaration and initialization, the value of a constant cannot be modified:


![Hoisting Constant ex.2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tzh648urw5l6bvlu0ym5.png)


The constants cannot be accessed before declaration because of the temporal dead zone. When accessed before declaration, JavaScript throws an error: ReferenceError: <constant> is not defined.


![Hoisting Constant ex.3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yoay9mivf1jyfo37ncyq.png)


const hoisting has the same behavior as the variables declared with the let statement.


![Hoisting Constant ex.4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6aouq4vgp7yk7gc49oi.png)

### Hoisting Functions <a name="variable-function"></a>
Hoisting in a function declaration allows using of the function anywhere in the enclosing scope, even before the declaration.
The following code from the start invokes a function, and defines it:

![Hoisting Functions ex.1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4toqrbbpbd2nmx965lip.png)

The code works nicely because equal() is created by a function declaration and hoisted to the top of the scope.

**Note:** Function declaration `function declaration function <name>() {...}` and function expression `var <name> = function() {...}` both are used to create functions, however have different hoisting mechanisms. 

The following sample demonstrates the distinction between both ways:

![Hoisting Functions ex.2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mhqatpt06ga6smczb1v0.png)


The sum is hoisted entirely and can be called before the declaration.
However subtract is declared using a variable statement and is hoisted too, but has an undefined value when invoked. This scenario throws an error based on the type of variable to which a function is assigned

- If the variable is var then the error is: `TypeError: subtraction is not a function.

-  If the variable is let or const then the error is: `ReferenceError: Cannot access 'subtract' before initialization`


### Hoisting Classes <a name="variable-class"></a>

The class variables are registered at the beginning of the block scope. But if you try to access the class before the definition, JavaScript throws `ReferenceError: Cannot access '<class_name>' before initialization`. 

So the correct approach is to first declare the class and later use it to instantiate objects.

Hoisting in class declarations is similar to variables declared with a let statement

Let's see what happens if a class is instantiated before declaration:


![Hoisting Class Example-1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvckmahuu8gwrqzuua5n.png)

The same goes with the class creation with variable declaration statement:


![Hoisting Class Example-1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvrryouzypw1539rodzg.png)


### Conclusion <a name="conclusion"></a>
The summary of the post is 

- Hoisting allow us to use variables, but it depends on the type of variable you are using.

- Hoisting allow us to use functions before the declaration, but it depends on in which way you are declaring the function either the simple declaration or with a variable.

- Hoisting the var variable allows us to access/use the variable before declaration but the value will be undefined before initialization.

- Hoisting the let variable caused a `RefrenceError` if you access/use the let variable before a declaration.

- The declared but not initialized let variable by default has an undefined value 

- const hoisting has the same behavior as the variables declared with the let statement.

- The const variable must be initialized at the time of declaration.
 
- Classes must be defined before accessing it otherwise the program will through an error `ReferenceError: Cannot access '<class_name>' before initialization`




Exploring new concepts in #JavaScript and sharing with others is my passion and it gives me pleasure to help and inspire people. If you have any suggestion or want to add something please comment.

If you liked the post follow me on: <a href="https://twitter.com/abidullah_786">Twitter</a>, <a href="https://www.linkedin.com/in/abidullah786/">Linkedin</a> and <a href="https://github.com/abidullah786">GitHub</a>!