DEV Community

Cover image for Hoisting in JS
therealsuhail
therealsuhail

Posted on

Hoisting in JS

Hey geeks, today let's read about hoisting in JS.

Hoisting is one of those fundamentals which i feel every JS developer should know.
In simple terms, hoisting allows you to use functions and variables before they are declared.
Let us look at the code below

console.log(name)
var name = 'hello JS'
Enter fullscreen mode Exit fullscreen mode

In this case, JS will not throw any error rather it outputs 'undefined'. This is what hoisting is all about. It happens since JS allocates memory to variables and functions followed by the execution. In the memory allocation phase, variable name is being initialized with undefined , that is why it does not throw any error. Knowing about execution context will help you understand hoisting in a better way. You can check my article on execution context here

Variable hoisting

Variable hoisting behaves differently depending on how the variables are declared. Let us take a look at the code below

console.log(testVar)
let testVar = 'hello JS'
Enter fullscreen mode Exit fullscreen mode

It is quite surprising that it throws a reference error unlike var. const also exhibits the same behaviour. we get such errors when let and const are in temporal dead zone. Temporal dead zone is nothing but the time between the variable is declared and assigned value.

let and const were introduced in ES5 to avoid using variables before their declaration. It is to be noted that interpreter hoists let and const, but in some other memory space, whereas in case of var it is hoisted in global execution context.

Function hoisting

Functions are also hoisted in the same way like variables. Let us take a look at the following code.

getName()
function getName() {
    console.log("function")
}
Enter fullscreen mode Exit fullscreen mode

Here it outputs 'function' since getName is allocated memory before execution.

let us look at another example

getName()
const getName = () => {
  console.log("Inside function")
}
Enter fullscreen mode Exit fullscreen mode

Here you will be surprised to see that it throws reference error unlike the previous example. It is because 'getName' behaves like a variable here. Only function declarations are hoisted and not function statements.

Discussion (1)

Collapse
nicklane profile image
Nicholas Lane

Whilst I generally understand how hoisting works on a surface level, I assume it's still good practice to define or initialise your variable before you try to access it?
Is hoisting a thing just to help code be interpreted despite there being some human error?