Javascript Review: Hoisting

404-Not-Found
1 min readSep 25, 2020

I was reviewing some old material in my curriculum and came across the term hoisting. By definition, hoisting means to pull or raise something up, so how does this apply to Javascript?

In Javascript, this concept is applied to your declarations, variables and pulls them all to the top of the script. For example let’s look at a some code as an example.

function whatIsLove?(){
console.log(love)
let love= "Baby don't hurt me";
}

What do you think our function above here would log? “Baby don’t hurt me?” or something else?

If you said something else, then you are correct! We actually get undefined as the output of this function instead. Why? Because of ‘hoisting’. Javascript is actually, doing the following:

function whatIsLove?(){
let love;
console.log(love)
love = "Baby don't hurt me"
}

It actually, declares the variable love first then assigns the value “Baby don’t hurt me”. Javascript treats declarations and assignments as two different steps!

As you can see this can probably cause some bugs in your code and unexpected results, so what’s the key lesson here? For a best practice always declare your variables at the top to avoid potentially hours of debugging later on down the road.

--

--

404-Not-Found
0 Followers

I enjoy long naps on the couch, deep conversations about video games, and romantic dinners with anime.