Hoisting in JS

JakePino
2 min readJan 9, 2021

--

Let’s take a look at hoisting, a tricky concept in JavaScript. First, what exactly is hoisting?

Hoisting is where we can reference variables and invoke functions in your scope before you’ve actually defined them. Traditionally, you’d think in order for your code to recognize a function, it has to be coded in order like so.

function helloFunc() {
return "Hello World"
}
helloFunc()
// "Hello World"

However, because of hoisting, we can actually do this if we wanted.

helloFunc()function helloFunc(){
return "Hello World"
}
// "Hello World"

This is due to hoisting, which happens as part of the JavaScript engine. Javascript has a two-phased process; a compilation phase and execution phase. The first phase, the compilation phase, stores our declared variables and functions in its memory, and skips over the invocations. By the time the JavaScript engine reaches the execution phase, helloFunc() has already been created and stored in memory, and the code gets read line by line from the top (best practice, you should still declare your functions before you invoke them, but it’s still cool!).

Hoisting gets it’s name because our code appears to be “hoisted” to the top, despite the fact that the actual code doesn’t move places at all.

Things with hoisting get a little tricky with variables, so lets take a look.

Hoisting variables only works with declarations but not assignments. An example of each:

var myName
// declaration
myName = "Jake"
// assignment

Now, if we were to try to hoist a variable we assigned, we would get back something like this:

console.log(hoist)
var hoist = "hoisted"

However, if we were to declare jake first and then assign it later, it would work as we expect now with hoisting:

console.log(hoist)var hoisthoist = "hoisted"

However, when trying to hoist variables inside functions, things get even a little more complicated.

function myName(){
var jake
console.log(jake)
jake= "jake"
}

Based on what we know about hoisting so far, you would think that this would print “jake”. However, we get undefined. Whomp whomp. However, if we return jake, we get something different.

function myName(){
var jake
console.log(jake)
jake= "jake"
return jake
}
// undefined
// jake

This works because var jake initially is undefined and it remains undefined when it hits the console.log during the execution phase. Then jake gets assigned and thus, the return is what wanted initially. Moral of the story, try to declare and assign your variables before calling on them. I hope this helps!

--

--

JakePino
JakePino

Written by JakePino

California native, living in NYC., Software Engineer.

No responses yet