Hoisting

Hoisting

Let's learn hoisting.

Let's first understand what is Hoisting.

Prerequisites

This blog assumes you're familiar with the let, const and var keywords, as well as how to use them.

What is Hoisting?

Hoisting is the phenomenon in JavaScript by which we can access variables and functions even before we declared them.

Variable Hoisting

see the example below

console.log(num); //undefined
var num = 2

Here we are trying to access the variable before the declaration and getting undefined

let's try this example.

num = 2;
console.log(num); // 2
var num;

here we are initiating the variable and then trying to access it before declaring it. num is getting hoisted and we can access its value.

but this is not the case with variables declared with let and const.

when we declared a variable with let and try to access it before its declaration we will get ReferenceError.

console.log(num) // ReferenceError: Cannot access 'num' before initialization
let num = 2

same case with const.

Function hoisting

let's look at function hoisting. we can also access a function before defining it.

for example:

num()
function num() {
  console.log(2) // 2
};

but this is not with arrow functions. when we will try this using the arrow function we will get TypeError.

num()
var num = () => {
  console.log(2) //TypeError: num is not a function
}

here javaScript assumes this as a variable and will throw an error.

Conclusion

Thanks for reading this. If you found this blog helpful do like and comment. Feel free to reach out to me on LinkedIn.