Master the Art of Hoisting in JavaScript: A Beginner's Guide

Master the Art of Hoisting in JavaScript: A Beginner's Guide

Hello developers, In this blog we will understand the "so complicated" topic of Hoisting in JavaScript in an utterly simple way!

Hello developers, in this blog we will be demystifying the seemingly complicated topic of Hoisting in JavaScript. So let's dive in!

Introduction

Let's start with an example, consider this code:

console.log(a);
sayHello();

var a = 5;
function sayHello(){
    console.log("Hello World");
}

At first glance, you might think that everything about this code is wrong and the code is full of errors like:

  • We are printing the value of a variable even before it is declared.

  • We are calling the function sayHello even before it is declared.

But actually this is a perfectly valid JavaScript code and it will output the following in the console:

2 Phases of Code Execution

The reason why most people find Hoisting complicated or confusing is because they don't have a firm understanding of How the JavaScript code executes behind the scenes. I have written an entire blog about it discussing the 2 main phases in which the Javascript code executes, you can find it here. But we will be covering it in brief in this blog itself.

You need to understand that any JavaScript code executes in 2 phases,

In the first phase, JavaScript skims through the entire code looking for functions and variables to which it assigns memory to. It is to be noted here that in case of variables, only memory is allocated to them but no value is assigned and in absence of any value, the variable takes up undefined as the default value. If we consider the example of the above code, Here we have 1 variable i.e, a and 1 function that is sayHello . Hence, after Phase 1 the memory space of this code will look like this:

This is a visual representation of the memory space of the JavaScript code where we can see that memory has been allocated to the variables and the function. We can actually see this inside the browser too!

Note that we are still in Phase 1, where no line of code is executed and only memory has been allocated to the variables and functions.

Have a look at this image:

Here we see, that I have paused the execution and till here, not a single line of code is executed ( which will happen in Phase 2 ) and our Phase 1 is over. This means that the variable a and the function sayHello has been allocated memory. Let's look where is it present in the next 2 images.

In the above 2 pictures, you will see that inside the global object which is window, memory has been allocated to the variable and function in the way it should have been.

Now, comes Phase 2 - The Code Execution Phase!

After Memory has been allocated and Phase 1 has ended, Phase 2 begins!

In this phase, JavaScript will run the code line-by-line. Here the assignment of value to the variables and function execution on invocation will take place.

Distorted Concept

Whenever we say that "The JavaScript code is Running/Executing", most of the times we are referring to Phase 2. It is to be kept in mind that before execution happens, memory has already been allocated to the variables and functions that are used in the code in Phase 1.

Keeping in mind that memory has already been allocated to the variables and functions, even before a single line of code is executed, let's head over to Phase 2:

//Phase 1 has ended
//Phase 2 begins - Code is Executed line by line.

console.log(a); // JavaScript searches for "a" in the storage and prints "undefined" because "a" has already been allocated memory but no value has been assigned to it in Phase 1, thus it will have the default value of "undefined" 

sayHello(); // Here JavaScript searches for the function sayHello() in the storage and on finding it, it will invoke sayHello, thus "Hello World" will get printed in the console.

var a = 5; // Here, actual assignment takes place and 5 will get assigned to the variable "a".

//There is nothing to execute in the below peice of code as it is just a function declaration. Function declaration executes nothing unless it is invoked.
function sayHello(){
    console.log("Hello World");
}

//Final Result in Console:
undefined
Hello World

With that said you probably get why the above mentioned code, which seemed to be full of errors is actually a correct piece of code. This is called Hoisting.

Hoisting is a concept in JavaScript in which variables and functions can be accessed even before they are declared!

Conclusion

Let's summarize what we learnt in this blog post:

In this blog, we discussed about the concept of Hoisting in JavaScript

  1. Hoisting is a concept in JavaScript in which variables and functions can be accessed even before they are declared!

  2. The JavaScript code executes in 2 main phases: The Memory Allocation Phase (Phase 1) and the Code Execution Phase (Phase 2).

  3. When we say, the code is running/executing, we generally refer to Phase 2. It needs to be kept in mind that the variables and functions we access in Phase 2 are already allocated memory in Phase 1.

  4. Hence, if we try to access a variable before it is declared, the value will be undefined and if we call/invoke a function before it is declared, the function will execute normally, without any errors popping up.

With this we come to the end of the blog. I hope you liked it and learnt something valuable from this blog post, if so a like would be appreciated!

About Me:

Hey there, My name is Krish Jaiswal, I am a Computer Science student from India, currently learning about Web Development and making an attempt to share my learning in public. I am open for Development and Technical Writing roles. If you are interested in hiring me, drop an email here: krishvp4856@gmail.com

Connect with me here:

Twitter: @Krish4856

GitHub: @KrishJ4856

Did you find this article valuable?

Support Krish Jaiswal by becoming a sponsor. Any amount is appreciated!