We have two different way for doing function expression in JavaScript:
Named function expression (NFE):
var boo = function boo () {
Naming functions is useful if they need to reference themselves (e.g. for recursive calls). Indeed, if you are passing a literal function expression as an argument directly to another function, that function expression cannot directly reference itself in ES5 strict mode unless it is named.
For example, consider this code:
setTimeout(function sayMoo() {
alert('MOO');
setTimeout(sayMoo, 1000);
}, 1000);
It would be impossible to write this code quite this cleanly if the function expression passed to setTimeout
were anonymous; we would need to assign it to a variable instead prior to the setTimeout
call. This way, with a named function expression, is slightly shorter and neater.
It was historically possible to write code like this even using an anonymous function expression, by exploiting arguments.callee...
setTimeout(function () {
alert('MOO');
setTimeout(arguments.callee, 1000);
}, 1000);
... but arguments.callee
is deprecated, and is outright forbidden in ES5 strict mode. Hence MDN advises:
Avoid using
arguments.callee()
by either giving function expressions a name or use a function declaration where a function must call itself.
(emphasis mine)