JavaScript: What is Hoisting

Jonathan Wong
3 min readSep 27, 2020

What is hoisting, you ask? If you’re new to JavaScript, this may be a confusing topic for you as it has been for me initially! Luckily, I’m here to help. To give you a brief explanation at first, it refers to how variable and function declarations are “moved to the top” in the context of the scope they’re in. The reason for the quotation marks are because it’s not in a literal sense as if the code literally changes place. So if it’s not in a literal sense, what sense is it? It refers to how the JavaScript compiler reads the code. It’s a bit confusing but I’ll give some examples to show you what I mean.

If you were to try to console.log something traditionally, you would do something like this.

var example = “It works!”
console.log(example)

Let’s say you wanted to hoist the declaration. What would that look like?

console.log(example)
var example
example = “It works!”

If you ran this in your code, what do you think would happen?

undefined
It works!

The statement gets printed but you get undefined at first! Let’s go over why that happens. We’ve seen the statement get printed but why? The reason we get undefined instead of a huge error that prevents us the statement even printing is because the compiler acknowledges that the variable exists but it wasn’t assigned a value yet.

You may have noticed I also used var! Why is that, considering that most people avoid it ever since let and const were created. There’s a specific reason for that and you may have guessed it. Although let and const are hoisted in their declaration, hoisting differs between all three.

This has to do with initialization. While variable declarations and function declarations are hoisted, initialization is not. There are times in which let declarations are hoisted but I would advise the person to be careful. However with const, you will definitely get a reference error. var declarations can also be accessible even outside the scope they’re used in because they are function-scoped and not block scoped unlike let and const.

So now what is the purpose of hoisting or why should you use it? From my research, it would appear that hoisting was never an intended feature but just how the browser interprets JavaScript. I personally avoid using it although I don’t have anything against it. I would say as a disclaimer for anyone who decides to hoist, to be wary as it may cause issues in your own code.

--

--