What is hoisting?

Hoisting is the process of putting all declarations, such as variables and functions, into memory during the compile phase.

One of the biggest myths around hoisting is that all variable and function declarations are moved physically to the top of your code. This is not true.

But instead, variable and function declarations are put into memory during compile phase and stay exactly where we typed them.

So exactly how are var/let/const and functions hoisted.

Here are some examples:

Variables declared with var will be hoisted and initialized with undefined. This is why when we try to console.log(a) prior to initialization, we get undefined.

Variables declared with let and const, are hoisted, but not initialized with undefined. They can be accessed only after initialization, otherwise we receive a ReferenceError. This is because of the Temporal Dead Zone, a time window where the variable exists but it still uninitialized.

But what about with functions?

Well it depends how we declare our functions. See below.

Traditional function declarations will be fully hoisted thus making function accessible throughout our code.

But with function expressions, we are unable to call a function before it has been declared. This is why the 3 functions declared with variables give us an error. In order to solve these errors, we have two options. Either change the function expression to traditional function declarations or call the function after the declarations.