Hoisting

Hoisting represents the process of accessing variables before they are defined. This concept may sound a little strange, but it has to do with how the JavaScript compiler works. The code is compiled in two passes. On the first pass, the compiler gets all variable declarations, all identifiers. In this case, no code is executed, methods are not called. On the second pass, the actual execution occurs. And even if the variable is defined after direct use, no error will occur, since the compiler already knows all the variables during the first pass.

That is, as if there is a raising of the code with the definition of variables and functions up to their direct use. Hoisting is translated into English as hoisting, which is why this process is called so.

Variables that are hoisted are set to undefined.

For example, take the following simple code:

console log(foo);

Executing it will throw an errorReferenceError: foo is not defined

Let’s add a variable definition:

console log(foo); // undefined
varfoo = "Tom";

In this case, the console will print the value “undefined”. On the first pass, the compiler learns about the existence of the variable foo. It gets the value undefined. On the second pass, the method is called console.log(foo).

Let’s take another example:

 
var c = a*b;
var a = 7;
var b = 3;
console log(c); // NaN

Here is the same situation. Variables a and b are used before definition. They are set to undefined by default. And if we multiply undefined by undefined, we get Not a Number (NaN).

The same applies to using functions. We can call the function first and then define it:

 
display();

function display(){
    console.log("Hello Hoisting");
}

Here, the display function will work safely, despite the fact that it is defined after the call.

But this situation must be distinguished from the case when the function is defined as a variable:

display();

var display = function (){
    console.log("Hello Hoisting");
}

In this case, we will get an error TypeError: display is not a function. On the first pass, the compiler will also get the display variable and set it to undefined. On the second pass, when it will be necessary to call the function that this variable will refer to, the compiler will see that there is nothing to call: the display variable is still undefined. And an error will be thrown.

Therefore, when defining variables and functions, one should take into account the twists and turns of such an aspect as hoisting.