JavaScript Hoisting

JavaScript Hoisting

ยท

2 min read

Have you heard the name JavaScript Hoisting? If not, let me show you some magic.

What will the output of this code:

var x = 7
function myName() {
    console.log("My name is Suvadeep");
}
myName();
console.log(x);

It's easy, right?

Now if I change the code a little bit, what will be the output?

console.log(x);
myName();

var x = 7
function myName() {
    console.log("My name is Suvadeep");
}

Now if your answer is the same as like before, it's wrong. Now question why?

Ans: In JavaScript, every variable is stored in the memory and this time the variable is stored it can't get the value and it will be stored as undefined.

Original output:

But why the function is not giving us any trouble?

Ans: In JavaScript, functions are not treated as variables. It can give you the proper output. Weird right? ๐Ÿ˜‚

How to check this?

Ans: open chrome dev tools and start a debugger. After that point where you want to debug your code. Then go to the scope and you can check the x and the function.
x will be undefined here.

Now, what will happen this time?

console.log(x);
myName();

function myName() {
    console.log("My name is Suvadeep");
}

This time it will give you an error( x is not defined)

Output:

Now x is not defined and undefined is a different thing. Don't get confused. Let's log the function this time.

console.log(myName);

function myName() {
    console.log("My name is Suvadeep");
}

This time you will get the whole function value.

output:

This is also an obvious thing. Now let's use the arrow function.

myName()
var myName =()=> {
    console.log("My name is Suvadeep");
}

This time it will create some trouble. It will show an error (Uncaught TypeError: myName is not a function).

Output:

So only for a simple function it will work and for others, it will not work.

This is a simple note about JavaScript Hoisting. Hope you like it.

ย