What the heck is hoisting?

This is a topic that I have been avoiding (mainly because I don’t feel like I understand it enough).  I figure that we have to tackle the idea eventually, though.  Hoisting is a JavaScript mechanism where variable and function declarations are moved (or hoisted) to the top of the scope before the code is executed.

Of course, there are a heck of a lot of caveats to be aware of.  Hoisting only moves the declarations and not the assignments.  Additionally, it won’t hoist anything that uses the let or const keywords and it won’t hoist function expressions or arrow functions.  So, what can you actually do with this?

See the Pen
JavaScript Hoisting – Part 1
by Joe Steinbring (@steinbring)
on CodePen.

As you can see in the above example, we moved the declarations below the assignments and the places where we are using the variables and it executes fine.  If we remove the declarations completely, it doesn’t really matter, though.

See the Pen
JavaScript Hoisting – Part 2
by Joe Steinbring (@steinbring)
on CodePen.

It is this fact that makes me think that this hoisting malarkey is kind of dumb.  So, what happens when you try to use let instead of var?

See the Pen
JavaScript Hoisting – Part 3
by Joe Steinbring (@steinbring)
on CodePen.

What you get is a “Uncaught ReferenceError: Cannot access ‘fname’ before initialization” error.  Frankly, that is what you would expect to see.

Have a comment, question, or concern?  Did I get something wrong in my analysis?  Do you secretly love hoisting?  Feel free to drop a comment, below.

 

[ Cover photo by Fas Khan on Unsplash ]

Leave a Reply

Your email address will not be published. Required fields are marked *