Javascript Hoisting

If you’re new to Javascript, then you’ve probably run into the problem of writing variables or functions in some part of your code and calling them then getting undefined returned. One of the many reasons this could be is due to something called hoisting. Hoisting can cause many headaches in your code, so to make sure you don’t encounter the same problems I did, we’ll get right into it.

What is hosting?

Variables and functions are hoisted to the top of their containing scope. In English that means that they’re declared, but not initialized or implemented. Let’s see some code to demonstrate this:

The above will run just fine because greet exists in the global scope and can be accessed within the sayHello function.

Let’s look at another example and see what happens:

What do you think will happen?

The first console.log will return undefined, but the second will return our string “Hello world again from inside the function”. Why is that? It’s because our variables are being hoisted or pushed to the top of our sayHello() function. They’re being declared, but not initialized. Behind the scenes this is what’s going on:

A new greet variable is being declared before any other code is ran inside the function. Since it’s declared and has not been initialized or had anything assigned to it, when we call console.log the first time we receive undefined, but after we initialize it and call console.log a second time we see our string returned to us.

Hoisting Functions:

There are two ways to create functions in Javascript. The first way is called function declaration which looks like this:

The second is by using a function expression, which simply means assigning a function to a variable:

The declaration of a function expression is hoisted to the top, but not the implementation of it. Calling the two different functions within our earlier example demonstrates this:

The above will return an error because the function has been declared, but not initialized at the top of a scope due to it being a function expression. If we used a function declaration instead, then we could call the function just fine because when function declarations are hoisted they’re also initialized.

Hoisting is an intricate part to understanding how scoping works in Javascript. If this post helped you, then you’ll be able to quickly identify when/if this bug rears its ugly head in your code.Related

Originally published at on September 13, 2015.