1

Possible Duplicates:
Javascript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?

Today I stumbled upon the following phenomenon:

foo();
bar();

function foo()
{
    console.log("inside foo");
}

var bar = function()
{
    console.log("inside bar");
}

FireBug complains with the following error message:

bar is not a function

Several tutorials claim that function f() and var f = function() are basically the same thing. Evidently, they are not, but what exactly is going on here?

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • 1
    dup: http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascript – davin Jul 07 '11 at 16:04
  • Just to clarify: This is not only a phenomenon of *anonymous* functions, but of function *expressions*. You can also have *named* functions as function expressions and you will see the same effect, but you cannot have anonymous function declarations. – Felix Kling Jul 07 '11 at 16:06

1 Answers1

1

Function declarations are available anywhere in the scope they're defined in, even before their physical definitions.

var bar = function() { ... }; is a normal variable that happens to hold a function. Like all other variables, it can only be used after its assigned.
(You cannot observe the future value of a variable)

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964