Generally, we all have heard of the term ‘hoisting’ with reference to flag hoisting.
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 behavior and their explanations. Hope it will help you in understanding hoisting better.
Only declarations are hoisted, a memory placeholder is granted which points to undefined as of now. Definitions still execute at the same place where the code is written.
In the case of functions, the behavior becomes a little tricky. Functions are hoisted along with their body. This is the reason why we can call a function even before it’s declaration. Still they work just fine.
3. Statements and definitions
Statements and definitions stay in the same place where they are written and are not hoisted anywhere. Printing a value before it’s definition will still give us expected results which can be an ‘undefined’ or previously provided value depending upon our 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 only assigning an anonymous function to a variable. Since the variable definition is not executed during hoisting, it will not know anything about the assigned anonymous function until the 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.