Back to Blog

Two ways of declaring functions

on March 15, 2010

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

1var foo = function () {};
2function 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

1function test() {
2  foo();
3  var foo = function () {
4    console.log("foo");
5  };
6}
7test();

Above code is same as one given below.

1function test() {
2  var foo;
3  foo();
4  foo = function () {
5    console.log("foo");
6  };
7}
8test();

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

1function test() {
2  foo();
3  function foo() {
4    console.log("foo");
5  }
6}
7test();

Above code is same as one given below.

1function test() {
2  var foo;
3  foo = function () {};
4  console.log(foo());
5}
6test();

Conclusion

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

1function test() {
2  foo(); // TypeError "foo is not a function"
3  bar(); // "this will run!"
4  var foo = function () {
5    // function expression assigned to local variable 'foo'
6    alert("this won't run!");
7  };
8  function bar() {
9    // function declaration, given the name 'bar'
10    alert("this will run!");
11  }
12}
13test();

You might also like

If you liked this blog post, check out similar ones from BigBinary