- Function Declarations
- Function Expressions
In this post, We'll can understand function hoisting by looking at how function declarations and function expressions behave in the creation and execution phase.
**Hoisting Function Declarations
we'll analyse the below example to understand how function declarations are hoisted -
The below happens in the above example -
- When the execution phase starts and the add function is called the full function body is already available in the execution phase so this program outputs 3.
**Hoisting Function Expressions
The way function expressions are hoisted is similar to how variables get hoisted as a function expressions is simply assigning an anonymous function to a variable so that we can later execute that by referring to the variable name.
We can conclude from above examples that hoisting the function expressions happens the same way as the variable hoisting.
- In the first example, we get an error
add is not a functionas the variable add was hoisted in memory with a value of
undefinedthus the Js Engine expects add to be undefined and not a function so it throws an error in case we access it before initialisation.
- For the second one i've replaced
letand it gives an error again as let/const declarations are only given memory in the creation phase but not a value so it results in the error
cannot access 'add' before initialisation.
- The third example does print the expected output as we are accessing the variable add only after its initialised in out program so the variable add gets initialised to the anonymous function and we get the output 3 on calling it.