DEV Community

Sumit Chahar
Sumit Chahar

Posted on

Function Hoisting In JavaScript

In the previous post we talked about variable hoisting. Now we are going to look at function hoisting in JavaScript.

There are two main types of functions in JavaScript -

  • 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 -

Image description

The below happens in the above example -

  • In the creation phase the javascript engine encounters the function keyboard and the default behaviour is that when a function declaration is encountered it's hoisted in the memory with its complete function body.
  • 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.

Image description

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 function as the variable add was hoisted in memory with a value of undefined thus 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 var with let and 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.

Top comments (0)