Hoisting in javascript

Forgetforget
1 min readMar 25, 2022

It is the default behavior of JavaScript in the JavaScript compiler.

var x = 7;function getName = () =>{
console.log("Hello World");
}
console.log(x);
getName();
7
Hello World

When we console .log any variable before defining and initialization but the value is undefined is shown in the console of chrome browser. if you want to know why it is so continue with an article?

When JavaScript starts compiling the code first phase is the memory creation phase. and in the memory creation phase memory is allocated for different variables and functions but for variable initialize and value is undefined is allocated but the value is assigned in code exception phase.

So when anyone uses the variable before the assigned the value is undefined which is assigned during the memory creation phase. this how hoisting behaves in JavaScript.

But for function whole code is written in JavaScript allocate the memory as written in code. so for function hoisting is different as compared to a variable.

Take an example :

console.log(x);getName();console.log(getName());
var x = 7;function getName = () =>{ console.log("Hello World");}

Output:

undefined // because call the variable before the initialization
Hello World // function invoking
console.log("Hello World"); // consoling the function

When any line executing the function or invoking the function new execution context is created in the call stack and when function execution is completed then execution context is pop out from the stack and control goes out to where it starts further codes execution is going out.

--

--