First I want to correct RoBorg: function abc(){} is scoped too — the name abc is defined in the scope where this definition is encountered. Example:
function xyz(){
function abc(){};
// abc is defined here...
}
// ...but not here
Secondly, it is possible to combine both styles:
var xyz = function abc(){};
In this case both xyz and abc are aliases of the same object:
var xyz = function abc(){};
console.log(xyz === abc); // prints "true"
When is this useful? When we want to play with a local and a "global" name for some reasons:
...
// we want to define the global function and cache it locally
some.really.really.long.scoped.global.name = function abc(){};
// now it is globally defined, yet we can access it locally
abc(1, 2, 3);
The snippet above avoids chained lookups by using its local alias making the access very fast.
Another compelling reason is the "name" attribute of function objects (not supported by IE browsers). Basically when you define a function like this:
function abc(){};
console.log(abc.name); // prints "abc"
its name is automatically assigned. But when you define it like this:
var abc = function(){};
console.log(abc.name); // prints ""
its name is empty — we created the anonymous function and assigned it to some variable.
Deep down JavaScript treats both statements differently: the former is the function declaration, while the latter is the function expression. That's the real reason why there is a difference demonstrated by RoBorg.
Fun fact:
var xyz = function abc(){};
console.log(xyz.name); // prints "abc"
Personally I prefer the "function expression" declaration because this way I can control the visibility. When I define the function like that:
var abc = function(){};
I know that I defined the function locally. When I define the function like that:
abc = function(){};
I know that I defined it globally providing that I didn't define abc anywhere in the chain of scopes. This style of definition is resilient even when used inside eval(). While this definition:
function abc(){};
depends on the context and may leave you guessing where it is actually defined, especially in the case of eval() — the answer is: it depends on browser.
- 44k
- 8
- 52
- 57