DEV Community 👩‍💻👨‍💻

Cover image for Hoisting in Javascript

Posted on

Hoisting in Javascript

Hello Guys today i am discussing about Hoisting in Javascript.

What is Hoisting?
Hoisting is a process in which the declaration of variables and functions are moved to the top in the scope by the interpreter.
We can move the declaration of variables to the top with default value(Only the declaration part not the initialization part) or we can use a function call before it's declaration and then after that we can provide the declaration part in the code.
Let's understand this with examples.

Example 1 - Variables Hoisting

var a = 10;
//output - undefined

let b = 20;
// output - ReferenceError: Cannot access 'b' before initialization

let c = 20;
//output - ReferenceError: Cannot access 'c' before initialization
Enter fullscreen mode Exit fullscreen mode
  • As you can see we have console logged the variables before declaring them.
  • It returns undefined in case of variable declared with "var" keyword because the declaration part is hoisted with "var" not initialization part.
  • In case of variables declared with "let" and "const" , it returns a reference error because "let" and "const" are not hoisted with default value.

Example 2 - Function Hoisting


function hoistedFunction(){
  console.log("This function is called before it's declaration")
//output - This function is called before it's declaration


function hoistedParameterisedFunction(a,b,c){
//output - 10 20 30


let hoistedArrowFunction = () => {
  console.log("This function is called before it's declaration")

//output - ReferenceError: Cannot access 'hoistedArrowFunction' 
//before initialization
Enter fullscreen mode Exit fullscreen mode
  • You can see we have called the function before it's declaration and still it gives the output because in case of function hoisting , the entire function declaration along with its body is hoisted so, it gives the desired output.
  • We can also pass parameters to the function call which is hoisted.
  • In case of Arrow function , we have assigned the anonymous arrow function to the "hoistedArrowFunction" variable , hoisting this will give a reference error same like in case of variable.

I have tried to explain this concept as much as i know and if there are more things with this concept please mention it in the comment section.

^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> <--

Also check these posts as well

Top comments (2)

varshithvhegde profile image
Varshith V Hegde

Thanks for the blog it was very helpful.

shubhamtiwari909 profile image
Mysterio Author

Welcome 😉😉

🌚 Life is too short to browse without dark mode