Explore Function Hoisting In Java Script

Posted By : Avilash Choudhary | 30-May-2018

Explore function hoisting in java script Hi Guys, Today we are going to learn to hoist in java script. As you all of know, java script has two types of hoisting.

* Variable hoisting

* Function hoisting

In this article, we are going to explain function hoisting, as it is very tricky. We can create function by two ways in java script, one way is function expression and other is the function declaration. Function declaration

function name(param1, param2) {
    // statements...... 
}

Function declaration hoists the function definition, these types of functions can be used before they are declared.

test(); // output - Testing.....
 function test() {
     console.log('Testing.....');
 }

NOTE: Never use function declarations inside if/else block In Function expression, we can use the function keyword

const myFunction = function [functionName] (param1, param2) {
    // statements....
}

NOTE: Java script does not hoist function expressions.

 test(); // TypeError: test is not a function
 function test() {
     console.log('Testing.....');
 }

Below are some tricky questions to understand function hoistings.

    var test = 1;
function testing() {
  test = 10;
  return;
  function test() {}
}
testing();
console.log(test);

In above example, if we do not pay much attention then we might think the output will be 10. but it has some complexity. Java script will hoist the test function and then it will look a like this

      var test = 1;
function testing() {
    // hoisted
function test() {}
  test = 10;
  return;
}
testing();
console.log(test);

Hoisted statement create local test variable and when we are assigning 10 to test, we are assigning to local test variable. when we console the test, it will print 1, because it is pointing to global test variable. Another example,

  function testing(){
    function test() {
        return 3;
    }
    return test();
    function test() {
        return 8;
    }
}
alert(testing());

The above example will alert 8 because java script will hoist both the functions and when we call the testing function it will return function who is returning value 8.

 function testing(){
    //Hoisted before
    function test() {
        return 3;
    }
    // Hoisted after
    function test() {
        return 8;
    }
    return bar();
    
}
alert(testing());

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..