Hoisting in JavaScript A-Z

Hoisting in JavaScript A-Z

ยท

3 min read

Hoisting is JavaScript's default behavior of moving declarations to the top.

We all read this. But what is exactly happened in hoisting? We will discuss the backend task of hoisting and many confusion about hoisting. Let's start.

At first, we should know what is declaration and initialization? Sometimes it creates confusion to understand hoisting.

var a; //declaration

a = 10; // initialization

Now we will understand what is the default behavior of moving declarations to the top with examples.

var c = 5;
var e = 6;
console.log(c);

How does javascript execute this code in the backend?

Javascript finds all the declarations first and takes them to top the code.

var c;
var e;
c= 5;
e =6;
console.log(c)

Javascript finds the c and e on the top. This is hoisting.

Now, what if we code like this. Is this workable or not?

console.log(c);
var c = 5;
var e = 6;

what is the output of console.log(c)? The answer is undefined. Because this code executes like this.

var c;
var e;
console.log(c);
c= 5;
e =6

When console.log(c) execute, there is no initialization value for variable c.

We can write this code like this, the output will be the same.

console.log(c);
c= 5;
e =6
var c;
var e;

Anyways, what if, we call the function before the function initialization? It will be error, undefined, or print the function value. Let's jump to the code.

var c = 10;
console.log(hoisting)
hoisting("blog")

function hoisting(name) {
    console.log("please like this" + " " + `${name}`);
}

It's print out the value. Now, Try to understand what happened here. Javascript allocated memory for variables and functions before the code was executed. In this initial level of memory allocated, variables are undefined, and function copies all functions and save them. But the array function doesn't print the value like this. Because the array function behaves like a variable when the initial memory is allocated. We will get a clear idea from this example.

console.log(a); // undefined
//a() // not initialize
var a = () => {
     console.log("a"); //a 
}
a();
console.log(a); //[Function: a]
a() 
function a() {
    console.log("a"); // a
}

What if the code is like this,

var a = 10;

function b() {
    console.log(a);
    var a;
}

b();

The answer will be undefined. If you think how or why? Let's see, how javascript handling this code here.

var a ;
a =10;

function b() {
    var a;
    console.log(a);

}

In the function, var a redeclared but don't initialize any value. So, the answer is undefined.

If you notice all my examples, I only use var. Because let and const hoist but you cannot access them before the actual declaration is evaluated at runtime.

I really hope you don't have any confusion about hoisting. Happy Coding ๐Ÿ‘จโ€๐Ÿ’ป

ย