Javascript Hoisting : Function Hoisting

In Previous article, We have looked into how Javascript Hoisting works.

Hoisting is Javascript’s default behavior of moving declarations to top of the file.

There are two types of Hoisting is there:

  1. Variable Hoisting
  2. Function Hoisting

Let’s discuss Function hoisting with example:

There are two ways for creating Javascript functions through Function declaration and Function expression.

Let’s first understand Function declaration:


function <functionName> ( ... params) {

[Statements of code ... ]

}

In Javascript, Hoisting works for Function too. Hence, Function declarations hoist the function definitions. Therefore, this function can be used before they are even declared.

Example:


myHoistedFunction();

function myHoistedFunction() {

console.log("This function is hoisted through Javascript Hoisting");

}

Behind the scene, Above code moves function declaration at the beginning of file and execute it when its being called.

Note: Never use, Function declarations inside if/else block else it won’t work.

 

Now, Let’s look at Function expression,

Function keyword can also be used to define a function inside an expression.


var callFunctionExpression = Function <strong>[<myFunctionName>]</strong>( ... params ) {

[Statements of code]

}

In above code, [<myFunctionName>] is optional. Therefore, it can be used as anonymous functions. We can use arrow functions as well.

var callArrowFunctionExpr = ( … params ) => {

[Statements of code]

}

This kind of Function expressions won’t be executed in Javascript.

Please let us know your feedback in comments. We will be more than happy to answer your questions.

One comment

Leave a Reply