Hoisting? What’s that? JavaScript Essentials

Emma Lowe
Webtips
Published in
2 min readJun 4, 2020

If you are new to coding or come from a background of using strongly typed languages, hoisting is most likely an unfamiliar term. Understanding hoisting is essential to mastering the often confusing world of JavaScript scope.

Photo Credits: Christina Morillo, Pexels.com

Have you ever written something along the lines of this in JS and been surprised to not receive an error?

This is all thanks to JavaScript hoisting. In JavaScript, variables are hoisted to the top of their scope. That means that during runtime, the interpreter views the above code snippet like this:

The interpreter first processes variable declarations and then executes code. But what about undeclared variables? Let’s take a look.

The interpreter does not process undeclared variables until the code assigning them is executed. This is why referencing cat produces an error while dog does not.

It is worth noting that undeclared variables have a global scope. It is best practice to declare and instantiate all variables before using them. More on JavaScript scope here.

Also note that functions and objects are also hoisted in JavaScript. Classes are not. If you attempt to create an object using a class before the class is defined you will receive a reference error.

Now, let’s slightly alter our first code block. Instead of using var, let’s declare our variable using the ES6 keyword let.

Let is more strongly defined than var and requires declaration and initialization before referencing a variable, function, or object.

If you enjoyed this article, give it a clap and check out my other articles!

--

--

Emma Lowe
Webtips
Writer for

Emma is a software dev who synthesizes information best through writing. She believes clear documentation and communication go hand in hand with good code.