DEV Community

kim-jos
kim-jos

Posted on • Edited on

How does Hoisting Actually Work in JS?

What Is hoisting?

Hoisting is the ability to access functions and variables before they are initialized. Most people seem to think that JS moves the code to the top of the file. But that is not the case. Let us figure out how JS makes hoisting possible (it all goes back to the execution context).

How does variable and function hoisting work in JS?

As we have seen in first part of the series, variables are assigned a value of undefined while functions are copied wholly in the memory allocation phase.

Let us see an example with code below. In the first console.log(sayhi), the function is not invoked so the whole function, not the returned value, is printed in the browser. In the second console.log(x), the browser prints undefined while the third console.log(x) prints 1. The reasoning behind this should be familiar to you if you read the first part of this series.

console.log(sayhi); // prints 'hi'

console.log(x); // undefined
var x = 1;
console.log(x); // 1

function sayhi() {
  console.log('hi');
}
Enter fullscreen mode Exit fullscreen mode

This whole process works this way because JS, in the memory component phase, copies functions and assigns undefined values to variables in the global object which is also known as window in the browser.

How does hoisting work for arrow functions?

Let's see an example.

sayHi(); // TypeError: sayHi is not a function
var sayHi = () => {
  console.log('hi');
}
Enter fullscreen mode Exit fullscreen mode
sayHi(); // hi
function sayHi() {
  console.log('hi');
}
Enter fullscreen mode Exit fullscreen mode

As we can see in the first example above, sayHi is a function but is declared as a variable instead of a function. We know that JS saves variables with a value of undefined which is why sayHi() cannot be invoked before sayHi() is declared. But if sayHi is declared as a proper function then sayHi() can be accessed before it is declared because, once again, JS copies the whole function before the code is executed.

Top comments (0)