Javascript | Hoisting Concept
Hi there… In this article I am going to explain a Javascript concept called Hoisting.
Get Duleep Alwis’s stories in your inbox
Join Medium for free to get updates from this writer.
What is Hoisting?
- This is a mechanism related to declarations of variables, functions, and classes are conceptually moved to the top of their containing scope during the compilation phase. Because only declarations are hoisted (not assignments), you can use these elements before they are written in the code or assigning values in the code.
- When we define variables, functions, classes there is a way to access them before initializing a value.
Let see variable hoisting with var , let , const
console.log(a);
var a = 1;
--> Output -> undefined. (No errors)
What happens internally.
var a; //hoisted declaration.
console.log(a); //undefined
a = 1 //Initialization happens later
----------------------------------------------
console.log(b);
let b = 1;
---> Output -> ReferenceError: b is not defined var: Hoisted to the top of its scope and initialized with a default value ofundefined. If you log the variable before its declaration line, it will returnundefinedrather than throwing an error.let&const: Hoisted to the top of their scope but not initialized. They enter a Temporal Dead Zone (TDZ) and will throw aReferenceErrorif you try to access them before their declaration line is executed.
Now let’s see functional hoisting with var, let ,const…
sayHi();
var sayHi = function(){
console.log("Say Hi");
}
//This will say sayHi() is not a function because Function expression Hoisting
//Not fully hoisted.
---------------------------------------------------------------
sayHiHi();
function sayHiHi(){
console.log("Say Hi Hi");
}
//This works because this is Function Declaration Hoisting (Fully Hoisted)
Internally
function sayHiHi(){
console.log("Say Hi Hi");
}
sayHiHi();
//Entire function definition is hoisted.
-----------------------------------------------------------------
For let , const
sayLet();
let sayLet = function(){
console.log("Hi sayLet");
}
---> This will give this | ReferenceError: Cannot access
---> 'sayLet' before initialization
So hoisting concept is a very important concept in Javascript . When writing codes in large javascript code bases , you will have to keep this in mind.
Let’s meetup in a another article … Until then happy coding with JS.





