JavaScript: Hoisting explained

Jaspreet Sidhu
3 min readFeb 18, 2019

Generally, we all have heard of the term ‘hoisting’ with reference to flag hoisting.
Well in javascript also, it is used for quite a similar behavior. Instead of a flag, we are hoisting functions and variable declarations here.

Functions and variable declarations are taken to the top of the functions they are executing in. If there is no parent function present, then they are hoisted to the top of the global scope.

Still, there are differences in what should be hoisted and how much to be hoisted.
Below are the different use cases, language behaviour and their explanations, hope it will help in understanding hoisting better.

1. Variables:
Only declarations are hoisted, a memory placeholder is granted which points to undefined initially. Definitions still executes at the same place where code is written.
This is the reason why below code prints ‘undefined’ and doesn’t throw any error of ‘undeclared’ variable.

2. Functions: In case of function, the behaviour becomes little tricky. Functions are hoisted along with their body. This is the reason why we can call a function even before it’s declaration and still they will work just fine.

3. Statements & definitions: Statements and definitions stays on the same place as written and are not hoisted to anywhere. Printing a value before it’s definition will still give us expected results which can be ‘undefined’ or any previously provided value depending upon your code.

4. Named function expression: Named function expression are executed in the same way as variables i.e. they will also return ‘undefined’ if called before it’s definition.
This is because we are just assigning anonymous function to a variable. Since variable definition is not executed during hoisting, it will not know anything about the assigned anonymous function unless and un-till it’s definition is executed.

It is important to understand this behavior as it could affect our code outputs and the way our code is parsed and executed.

Now since we are clear with what is hoisting and what can we expect while writing our code in javascript, let’s wait for my next blog where I’ll be covering WHY HOISTING happens.

--

--

Jaspreet Sidhu
Jaspreet Sidhu

Written by Jaspreet Sidhu

Application Developer @ThoughtWorks

No responses yet