Hoisting in JavaScript

Ignacio Ojanguren
2 min readNov 11, 2021

--

Note: Before reading this SBI(Small Bite of Information) I would recommend reading about Javascript Execution Context here.

Today’s SBI is going to start with a question regarding this following piece of code.

// Write on console the value of the constant "hello"
console.log(hello)
// Declare a new constant called "hello"
// and assign to it the value of the string "Hello World"
var hello = "Hello World"

Try running this piece of code. You will see on the console “undefined” but not an exception saying something like the variable wasn’t defined.

You may be asking yourself:

  • Why is undefined being printed when variable “hello” hasn’t been defined? Doesn’t JavaScript run line by line during the Execution Phase?

That is correct JavaScript during the Execution Phase executes line by line. However, if you remember from this SBI I wrote about Execution Context, there is a prior step to the Execution Phase.

That prior step is the Setup Phase. During this phase JavaScript initializes a bunch of objects like global, and this. Javascript also during this step, scans all the code and allocates space in memory for each variable in the code. Once the space for the variables has been allocated in memory, the Setup Phase initializes those variables with the value undefined. This whole process of allocating space in memory and initializing the variables with the value undefined is called Hoisting.

PS: There is an important detail I cannot forget about. Try replacing in the code var for const or let.

Aha!

What is happening now?

The most likely is that you are seeing the following error: “Cannot access ‘hello’ before initialization”.

During Hoisting JavaScript doesn’t initialize the const and let with the valueundefined, instead it leaves the constants empty. So, when JavaScript is trying to access the constant value “hello” it won't find anything in it.

But isn’t undefined the same as empty? (Leaving you with the cliffhanger here. Tomorrow's SBI will be about undefined and null, stay tuned)

TBH, this is probably the behavior you were expecting when you first started reading this article. This is a reason why nowadays in JavaScript the best practice is to use const and let instead of var, when declaring variables.

--

--

Ignacio Ojanguren

Over 3 years of experience as a Software Engineer at Privy, recently acquired by Attentive Mobile. I am Learning, and I hope I can share what I learn with you.