What's the point of naming function expressions if you can't really reference them by the names you give them?
var f = function g() {
console.log("test");
};
g(); // ReferenceError: g is not defined
What's the point of naming function expressions if you can't really reference them by the names you give them?
var f = function g() {
console.log("test");
};
g(); // ReferenceError: g is not defined
Oh, but you can reference them by that name. Those names just only exist inside the scope of the function.
var f = function g() {
// In here, you can use `g` (or `f`) to reference the function
return typeof g;
};
console.log( typeof g );
// It only exists as `f` here
console.log( f() );
One advantage that I find particularly useful is that it helps when debugging.
When an error occurs, you see the function name in the stacktrace in the console. Otherwise the line in the stacktrace would only refer to an anonymous function.
You can also make the purpose of the function clearer by giving it a name.
It's important if you create a recursive function that is passed around. When you name a function it then knows about itself, within its own scope.
Here I've created a sort of factory function that creates recursive functions. For the recursive functions to work properly they need to know about themselves.
You can imagine this applied in a broader sense, like returning a recursive function as a module export.
var
func = (function () {
return function rec (a) {
console.log(a);
return a >= 5 ? 'done' : rec(a + 1);
};
}),
invoke = function (f, args) {
return f.apply(null, args);
};
console.log(
invoke(func(), [1])
);
By very definition, what you have defined is not an anonymous function:
function [name]([param[, param[, ... param]]]) {
statements
}
Name:
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
Furthermore, a lot of peole would consider
var f = function() {
return 'test';
};
not to be an anonymous function since you can now invoke it by var name f()
and can now pass the function as a parameter to other functions by the name functionThatTakesCallback(f)
.
In my head, a true anonymous function has no name whatsoever such as something passed to a call back:
$('#id').on('click', function(){
console.log("I am anonymous");
});
or as a function run immediately:
(function(when){
console.log("run me :", when);
})("right now");
With the syntax you are using now, in ES6 (most non IE browsers implement this feature), f.name
is g
. This is useful when debugging
You could use it to recur:
var f = function g (n, m) {
if (n>0) {
return g(n - 1, m = m + 'meta');
}
return m + 'test';
};
console.log(f(10, 'super'));