Hoisted by your Own Var: Function and Variable Hoisting in JavaScript

Let’s take a minute to talk about function / variable hoisting. In JavaScript hoisting means that, regardless of where a function is declared, it is moved or hoisted to the top of whatever scope it’s been declared in. Okay, that explanation was a little fuzzy so let’s back it up with a quick example:

Alright, here we have a very simple script that first declares a global variable called myGlobal followed by a hoistMe method which contains its own declaration of the myGlobal variable and a series of alert messages. Let’s run this and see what happens.

In this example, you would expect that the first alert would say ‘Global’ instead of ‘undefined’. However, due to hoisting, our myGlobal variable is moved to the top of the scope that it’s been declared in and the value is overwritten. This means that our JavaScript interpreter actually sees our function like this:

As you can see, in this example, myGlobal is getting overridden and set to undefined when the function executes. Why would JavaScript decide to behave in this manner, you ask? Well, one of the main advantages of hoisting is that it gives you the flexibility to use a function before actually declaring it. As helpful as that may sound, I find such coding practices sloppy and error-prone.

Let’s take a look at an example using function statements:

Now, when you first look at this, you’d think that your alert would say 5 when in fact you get 15:

On top of the confusing result, we’ve always been taught that code written after a return statement can never, ever be run so this code should definitely not be behaving the way it is. Well, remember how we talked about variables getting hoisted to the top of the function declaration? The same occurs for functions. Despite how our code is written, our JavaScript interpreter is actually reading the code like this:

In the above example, the declaration of foo that returns 15 is overriding the declaration of foo that returns 5.

I hope this helps someone out there. If you have any questions, please leave a comment below.