Two ways of declaring functions and impact on variable hoisting

 
 

All the JavaScript books I read so far do not distinguish between following two ways of declaring a function.

var foo = function(){};
function foo(){};

Thanks to Ben today I learned that there is a difference .

When a var is used to declare a function then only the variable declaration gets hoisted up

function test(){
  foo();
  var foo = function(){ console.log('foo'); };
};
test();

Above code is same as one given below.

function test(){
  var foo;
  foo();
  foo = function(){ console.log('foo'); };
};
test();

When a function variable is declared without var then both variable declaration and body gets hoisted up

function test(){
  foo();
  function foo(){ console.log('foo'); };
};
test();

Above code is same as one given below.

function test(){
  var foo;
  foo = function(){};
  console.log(foo());
};
test();

Conclusion

Now it will be clear why foo() does not work in the following case while bar() does work.

function test() {
    foo(); // TypeError "foo is not a function"
    bar(); // "this will run!"
    var foo = function () { // function expression assigned to local variable 'foo'
        alert("this won't run!");
    }
    function bar() { // function declaration, given the name 'bar'
        alert("this will run!");
    }
}
test();
 
Neeraj Singh's profile picture

Comments