Hoisting in JavaScript

Learning javascript is more or less being confused about what you just learned. To get over this, I decided to write a blog about what I just learned, which is...you guessed it! Hoisting in javascript. In this series, we understand hoisting and the difference between let and var keywords. Let's get started! To understand hoisting, we must first understand what is declaration and initialization.

Declaration and initialization

When I first started to learn to program, I thought declaration and initialization were the same things. I know, stupid. Anyway, you are in safe hands now. So, what are they? A declaration is when you define the name of the variable. For example:

let name; //this is a declaration

notice that here, you are not assigning a value to the variable, you are just defining/declaring. Now, initialization is when you give a value to the variable you have defined/declared.

name = 'Karthik'; //initializing the variable

Both declaration and initialization can be done in the same line, like this:

let name = 'Karthik';

Now, if you are still not sure about this, think of them like this. There is a difference between declaring war and a war starting.

let war; // declaring war 
war = 'start'; // initializing/starting the war

Now, that you have understood what declaration and initializing are, let's move on to hoisting.

What is Hoisting?

It is a process where the declarations of variables and functions are allocated memory before the execution of the code. How does this help? Let's look at an example.

// invoking the function(similar to initializing a variable)
greet("Karthik"); 

//let's declare a function
function greet(name){ //will be executed first
    console.log('Welcome, ' + name!);
}

Now, if you observe the above code, you might notice that we are invoking the function before even the function is declared. If you thought that the above code will throw an error, you would be wrong. This will work because, as I defined above, declarations of variables and functions are allocated memory even before the execution of the code starts. What this means is, the declaration part is run first, then the invoking of the function happens. In simple terms, hoisting splits up the declaration and the initialization and moves the declaration to the top of the code. So, the output will be

'Welcome, Karthik!'

This was just the explanation of hoisting, in the next blog of this series, we'll look at the differences between the let and var keywords with our newfound knowledge about hoisting.