In this section we’re assuming you’re already familiar with scopes in JavaScript.
Hoisting is essentially a concept that JavaScript developers came up with to explain the process in which a JavaScript source code goes through in order to be executed.
So in this section we will explain the actual steps that need to be done when a JavaScript program is executing. And at the end you’ll see why they use the term hoisting in JavaScript to simplify these steps.
In JavaScript there are two steps that a source code goes through to be executed:
-
Compiling.
-
Execution.
To explain these two stages, we need a source code to explain each step on it and see what happens to that source code in that step.
So this is the source code that we will use:
var firstName = "John";
var lastName = "Doe";
function printFullName(){
const wlc = "Welcome";
{
console.log(`${wlc} ${firstName} ${lastName}`);
}
}
printFullName();
Note:
-
The compiler is way more complex than what we will explain in
this section. But many of these complexities are not part of the
discussion of this topic and so we simply glossed over them and give you
the simple version of the JavaScript’s compiler instead. -
Also if you don’t have any clue about what compilers are in
general, you might want to read the compiler section
first.
At compile time, the compiler will check the source code and define the scopes and declare each variable in that scope.
Note: declaration is different than initialization. Declaration means registering the name of each variable in each scope. But if that variable has values to be stored in its memory space, this is initialization and is done in the execution time and not the compile time.
So in the source code at the beginning of this section, the compiler will first define the global scope.
The global scope is the outer most scope that a JavaScript program can have.
So here the compiler will check the source code to see what variables it can find and register in the global scope.
If you take a look at the source code, you’ll see that the variables firstName, lastName and the function printFullName are in the scope of the global.
Note: Compilers first start by registering the functions and then the variables.
So the compiler will register these variables in the global scope.
Global scope: {
Function: printFullName;
Variables: firstName, lastName;
}
Note: again the compiler only registers the name of the variables but it doesn’t do the assignment operation for those variables or the execution of functions. These processes are done in the execution stage.
In JavaScript there’s term called JIT compiling which stands for Just in Time compiling. At its simplest form, this means the compiler won’t compile the entire source code at once before the execution!
For example compilers only compile the body of a function when that function is called! So in the example above as long as the execution engine doesn’t reach to the printFullName(); statement which is an actual call to execute the body of this function, the function won’t be compiled.
Basically in JavaScript the compiler and the execution engine are constantly switching their position of taking control of the program because of this.
But here for the sake of simplicity let’s say that the compiler goes into the functions and declare the variables on those functions before passing the control to the execution engine.
Basically let’s say the compiler does compile the entire source code before passing the control to the execution engine.
So after the compiler, declared every variable in the global scope, it sees that there’s a function named printFullName. So it will create a new scope for this function and will start to declare and register every local variables of this function into this new scope.
Here we have one variable named wlc. So this variable is registered in the scope of the printFullName function.
So in the scope of this function we will have:
printFullName: {
variables: wlc
}
Inside this function, there’s another block. So the compiler will create another new scope for that block as well. In this block there’s no variable and so no registration will happen here.
Basically the inner block in this example is something like this:
Inner Block: {
}
Note: these scopes are linked together. This means the inner most block of this example is linked to its outer scope which is printFullName and this printFullName scope also is linked to its enclosing scope which is the global scope for this particular example.
After the work of the compiler is done, the source code of our example is turned into something like this:
Global scope: {
Function: printFullName;
Variables: firstName, lastName;
}
printFullName: {
variables: wlc
}
Inner Block: {
}
firstName = "John";
lastName = "Doe";
printFullName();
In the execution stage there’s no var or let or const and function keywords anymore! It’s just the statements of assignments and execution of the functions.
Basically the output of the compiler will be used as the input of the execution engine.
Note: the body of the printFullName function when it is passed to the execution engine is something like this:
printFullName(){
wlc = "Welcome";
{
console.log(`${wlc} ${firstName} ${lastName}`);
}
}
Again this is the very simplified version of what the compiler does. Here we’re just trying to show the processes that a JavaScript source code needs to go through in order to be executed. So spare the details and focus on the main topic for now.
Now let’s see what will happen at the next stage when the execution engine takes the control:
Execution:
After the execution engine received the output of the compiler, it will search for the first statement to run.
So in our example the statements are:
firstName = "John";
lastName = "Doe";
printFullName();
In the first statement which is firstName = "John";:
The execution engine realizes that this is an assignment operation. So it first checks the scope in which this statement is defined (global scope in this case) to see if there’s a variable with the name firstName is registered or not.
If we take a look at the data that the compiler produced, we can see that there’s a variable with this name already registered.
So the execution engine will take the memory space that is linked to this variable and stores the value John into that memory space.
Alright, the work of this statement is done and now the engine moves on to the next statement.
In the next statement we have: `lastName = "Doe";`
Again the execution engine first checks to see if there’s a variable in the scope in which this statement is defined in (global scope for this case).
When it finds that there’s such variable, it will find its memory space and stores the value Doe into that memory space.
Alright, the work of this statement is done as well and now moving on to the next statement.
The next statement is: `printFullName();`
This statement is a function call. So first just like the other two previous statements, the execution engine will check the scope in which the statement is defined to see if this function is registered in the scope or not.
Well here in the global scope this function is registered and so the execution engine will use the memory address that is linked to the printFullName to invoke the body of this function.
After invoking the function’s body, the execution engine will start to execute the statements in that function.
Just to remind you, this is the output that the compiler produced for the printFullName function:
printFullName: {
variables: wlc
}
rintFullName(){
wlc = "Welcome";
{
console.log(`${wlc} ${firstName} ${lastName}`);
}
}
Here the first statement is `wlc = "Welcome";`
The first step of the execution engine is to check if there’s a variable with the name wlc is already registered in the scope of this function. If we check this scope we can see that there’s a variable with this name registered in this scope. So the execution engine uses the memory space that is linked to this variable and stores the value Welcome into that memory space.
After that the execution engine proceeds to the next statement.
Here the next statement is in the body of the new block and the statement is:
console.log(`${wlc} ${firstName} ${lastName}`);
The point of this statement is to send the values of the three variables to the browser’s console.
So when the execution engine reaches the variable wlc in this statement, it will first check the scope of the inner block to see if there’s a variable with this name registered in this scope or not.
As you might remember, the output of the compiler for this scope was:
Inner Block: {
}
Essentially it’s empty. So the execution engine will move one step above and will check the scope in which this inner scope is linked to (the printFullName scope in this case). It will then check this scope to see if the wlc variable is registered in this scope or not.
Because this scope has such variable, the execution engine will take the value that is stored in the variable and replace it in the target console.log statement.
So the statement after this operation will look like this:
` console.log(`Welcome ${firstName} ${lastName}`); `
Now the execution engine will start to resolve the second variable in this statement which is firstName.
First the engine checks the inner block for this variable. But because there’s no variable with this name registered in this scope, the engine will move to the scope that is linked to this inner block (printFullName) in this case.
So the engine will check that scope to see if there’s a variable with such name. Unfortunately there’s no variable registered with such name in the printFullName scope, so the engine will check the scope that is linked to the printFullName which is the global scope in this case.
After the engine checked the global scope, it finds the variable in this scope and so it will use the value that is stored in its memory and updates the target statement with the value.
So the target statement at this stage looks like this:
` console.log(`Welcome John ${lastName}`); `
The last variable that the engine needs to look for is the lastName variable.
So again the engine starts to look for this variable in the inner block scope. Obviously this block does not have such variable. So the linked scope which is the printFullName is checked next. The printFullName scope also doesn’t have such variable registered in its scope and so the engine will check the linked scope of the printFullName (the global scope in this case).
The global scope has this variable and so the execution engine will use the value that is stored in that variable and updates the target statement.
This is the updated version of the target statement:
` console.log("Welcome John Doe"); `
At this stage all the variables of the statement are resolved and so the final message will be sent to the browser’s console.
After that, the execution engine sees that there’s no other statement to execute in the body of the printFullName() function and so it will exit the function.
Also there’s no other statements to run after the printFullName() statement. So at this time, the work of the execution engine is also finished.
That’s how a program in the JavaScript is compiled and executed.
Now the term `Hoisting`:
Hoisting essentially refers to the work of the compiler. Developers use the term hoisting to say that before the execution engine starts to execute each statement, all the variables of that program will move to the top of the scope in which they are declared in.
This means if there’s a variable declared at the bottom of a scope but is called at the top of that scope, the execution engine still knows that the variable exist and this is because the process of hoisting!
Example:
<!DOCTYPE html>
<html>
<head>
<title>JS is fun :)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Output:</h3>
<p id = "link"></p>
<script>
console.log(firstName);
console.log(lastName);
var firstName = "John";
var lastName = "Doe";
</script>
</body>
</html>
Output:
Undefined
Undefined
The first two examples of this program are:
console.log(firstName);
console.log(lastName);
Here we’re trying to send the values of two variables to the browser’s console. But these two variables are declared and initialized after these two statements.
So according to the concept of hoisting, before the execution of the program starts, variables are hoisted to the top of the scopes in which they are declared in.
So the program above will be translated like this:
var firstName;
var lastName;
console.log(firstName);
console.log(lastName);
firstName = "John";
lastName = "Doe";
Even though this concept seems a good model to have when thinking about how JavaScript programs run, it’s better to stay with the more accurate one that we’ve explained at the beginning of this section.
So if we want to explain the last example based on the two stages model (compiling and execution) it would be like this:
Compiling Stage:
First the compiler will create the global scope and looks for variables in this scope to register.
There are two variables here:
firstName and the lastName.
So these two variables are registered in the global scope.
Now because there’s no other variable or function to be registered, the compiler will produce this data as its output and pass the control to the execution engine:
Global scope:{
Variables: firstName, lastName
}
console.log(firstName);
console.log(lastName);
firstName = "John";
lastName = "Doe";
Note: Again, after the compiler compiled the source code, all the var, let, const and function keywords are gone. Only the initializations and execution statements will be left for the execution engine to run.
Execution stage:
So here the execution engine will run the first statement which is:
console.log(firstName);
Here the engine checks the global scope to see if there’s a variable with the name firstName.
Because there’s one registered in the global scope, it uses its value (which is undefined for now) and updates the target statement with this value.
So the statement becomes console.log(undefined);.
For this reason the first output that we see in the browser’s console is undefined.
After that, the second statement that the execution engine will run is console.log(lastName);.
Here again the engine checks the global scope to see if there’s a variable with this name. Because there’s one registered with the global scope, the engine will use its value and updates the target statement as:
`console.log(undefined);`
The value is undefined because this statement like the firstName also has no value yet. So the second output that we see on the browser’s console is undefined too.
After that the execution engine executes the next statement which is:
firstName = "John";
Here because there’s a variable named firstName registered in the global scope, the engine will use its memory address and stores the value John in there.
The last statement that the engine will execute is:
lastName = "Doe";
Here again the global scope is checked for the variable named lastName and because there’s a variable with this name, the execution engine will use the memory space of that variable and stores the value Doe in there.
That’s how the program compiled and executed.
Note: If inside a scope, the execution engine finds an assignment to a variable but no scopes registered such variable, the global scope will automatically create that variable and this automatically created global variable will be used in the assignment operation.
Auto global variable creation only happens if the target variable is set on the left side of the assignment `=` operator. If we try to access a variable to get its value and not assigning a value to it, we will get a reference error instead.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JS is fun :)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Output:</h3>
<p id = "link"></p>
<script>
function sayHi(){
name = "Hello";
}
sayHi();
console.log(name);
</script>
</body>
</html>
Output: Hello
Here at the compile time, because the variable name in the body of the sayHi() function is not declared with keywords like var, let, and const keywords, it is not registered in any scopes.
Note: basically there should be one of the keywords mentioned above attached to a variable so that the compiler register that variable. Otherwise it is ignored by the compiler.
So when the execution engine reaches to this statement, it checks all the scopes including the global scope. But because it couldn’t find such variable, automatically in the global scope a variable with the name name is created and the value Hello is stored in its memory space.
After the execution of the sayHi() function, the call to the console.log(name); statement used the name variable in the global scope and sent its value to the browser’s console.
Note: There’s a concept called Temporary Dead Zone (TDZ for short) that is related to the declaration of let variables. Please check the TDZ section to learn more about this. It’s an important topic.