Hoisting

Before we start discussing what hoisting is, let us first look at a simple example:

Pretty straightforward: I declared a variable, initialized some value to it, and then logged it in the console.

Now let's look at the definition of hoisting:

Simply put, it means no matter where you declare functions or variables when the code is executed, they’re moved to the top of their scope.

According to the above statement, if I were to move my variable declaration to below the console log statement, it should work just fine. But that’s not the scenario. Let’s see why that is.

Now the question arises: Why I am getting undefined when I should be getting the myName variable? Is hoisting not working?

The simple answer is that hoisting is working just fine. If you go back to the definition of hoisting, it specifically says that only the declaration is moved to the top and not the initialization.

So in the above example, our variable declaration is moved to the top while it’s initialized value is not, and the reason why we are getting undefined is because it’s the default value of the declared variable in JavaScript.

If hoisting was not working, then we would have got an error that the myName variable is not defined.

So because of hoisting, we can use the variables no matter where they are declared in our code. However, using their value is a different scenario.