Hoisting in JavaScript

Recently I have tried to really dig deep with understanding JavaScript at a higher level, in my early days of learning to code it was pretty much a trial and error affair with putting in some code and then hacking away at it for ages afterwards when it wouldn’t do what I wanted it to. A problem arose some time ago when writing some code for a toy project when I realised I was unable to call a function before declaring it, when I was pretty certain that I had done so many times before. (I had never looked into the why’s and how’s that allowed you to call a function before it technically even existed in the script. I just assumed black magic!) I then realised that due to my function being what is known as an anonymous function the process of hoisting didn’t occur and hence I was unable to call the function before writing it.

I have since delved a bit deeper into studying hoisting and for anyone unfamiliar with the term it simply refers to a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

The hoisting does however only move the declaration, not the assignment itself. This in turn explains my predicament with not being able to call the anonymous function. As an example, see the code below –

You will notice that when you copy this code into your editor and then open dev tools in your browser, the above function renders as expected. This is due to the fact that it is a declared function, i.e the function keyword is called followed by the function name which of course can be anything we wish. This is by default ‘hoisted’. However, if we consider the code in the screenshot below –

This code will throw an error in the console, ‘Uncaught ReferenceError: Cannot access ‘myFunction’ before initialization’ due to the function not being declared. Hoisting naturally applies to any variable, if you declare a variable it is by default initialized immediately. To try and use a variable that is undeclared will cause an error. A general good rule to follow is to declare all variables at the beginning of your code to avoid any hoisting related bugs.

One of the things I remembered from attending a Front End Developer boot camp when I was just starting out was that my teacher was declaring all of his variables at the beginning of the script and even though I had always beared this in mind since, I didn’t really know the real reasons why we did this until more recently.

Having a grasp of hoisting will be very useful going forward if you use JavaScript or are in the process of learning it, I have personally been playing around with JavaScript for a while now and I am constantly learning new things every day. I hope to blog again soon with some other concepts, in the meantime happy coding!

0
0