What is Hoisting in JavaScript?

Tram Ho

Preamble

Those who are just starting to learn about Javascript will wonder when they encounter some use cases of variables and then declare them later. Because according to the general rule of most programming languages, to use a variable, we must declare it first.

This is possible because in Javascript there is a Hoisting mechanism, in this article we will learn the Hoisting mechanism in Javascript. To understand Hoisting, you must first understand Scope in Javascript.

What is Hoisting?

Hoisting is JavaScript’s default mechanism for moving all declared variables and functions to the top of the scope before they are executed.

Note that for this mechanism it only moves the declaration, and the value assignment stays the same.

Hoisting variables

The life cycle of a variable in javascript includes the following stages:

  • Declare
  • Initialize default value
  • Assign a value to the initialized variable
    However, because Javascript allows us to assign a value right after declaring a variable. Here’s how we usually do it:

Try to guess what the output of the following code is:

I guess a lot of people will think that the result is ReferenceError: hoist is not defined because we are accessing a variable that has not been declared before. But no, the output of the above code is undefined.
LOL why is that???

Javasript’s Hoisting mechanism has brought variable declaration to the top. Below I will describe what happened.

If you wonder where the declaration is put on the top, where is the top. The top is the highest position in the current scope.

Eg:

The above function is similar to this:

Hoisting functions

In Javascript there are two types of functions:

  • Function Declaration
  • Function Expression
    With function declarations, you start the declaration as the function operator, then assign it a name like the example below:

As for function expressions, you create a variable and then assign it to an anonymous function like the following example:

In Javascript, Function declarations have the Hoisting property, while Function expressions do not.
Let’s take a look at the following examples:

Haizzz… how do you feel about Hoisting here? Personally, I find Hosting can lead to our code being sloppy and difficult to manage. And the ES6 version was born to improve the Javascript problems encountered.

Summary

Above I have explained about Hoisting in Javascript. Show part of the difference between Function expression and Function declaration.

Refer

https://dmitripavlutin.com/variables-lifecycle-and-why-let-is-not-hoisted/

https://xdevclass.com/hieu-sau-ve-hoisting-scope-trong-javascript/

Share the news now