DEV Community

Cover image for Hoisting in javascript ?
sagar
sagar

Posted on

Hoisting in javascript ?

“Hoisting is behavior in javascript where all the variable and function declaration moved to the top of the containing scope during compilation phase before code execution”

You may came across this definition everywhere but “it is a myth that all the variable and function declaration physically top of the code ” This is not true!

But instead , In hoisting all the variable and function declaration already get assigned memory before code execution in the compilation and stay exactly where we typed them.

So exactly how var/let/const and functions are hoisted.

Here are some examples:

console.log(a) // undefined
console.log(b) // ReferenceError
console.log(c) // ReferenceError

var a = 10;
let b = 20;
const c = 30;
Enter fullscreen mode Exit fullscreen mode

Variable declared with var will be hoisted and during compilation time var variable assigned in memory with value undefined that why when we console var before declaration we get undefined

Variable declared with const/let will also hoisted but not initialized with undefined . we can not access them before declaration , otherwise we receive a ReferenceError. This is because of Temporal Dead Zone, a time where variable exist but not initialized .

But what about function

Well it depends how we declare our functions. See below.

greet1();
greet2();
greet3();
greet4();

//function declaration is full hoisted
function greet1(){
    console.log("greet1");
}

// TypeError: greet2 is not a function
var greet2 = function(){
    console.log("greet2");
}

 // ReferenceError: Cannot access 'greet3' before initialization
let greet3 = function(){
    console.log("greet2");
}

// ReferenceError: Cannot access 'greet4' before initialization
const greet4 = function(){
    console.log("greet2");
}
Enter fullscreen mode Exit fullscreen mode

Traditional function declaration is fully hoisted means we can call it throughout the code.

but with function expression , we are unable to it before it has been declared . This is why three function declared with variables gives us an error. So we have two option either we change the function expression to function declaration or call the function after declarations.

Top comments (0)