3

In some Javascript libraries published on the web I find code like this:

var foo = function foo() {};

Example: https://github.com/Financial-Times/polyfill-service/blob/17fce11dc543af37b3fa8ef8a264056ef0f5f585/polyfills/Math.sign/polyfill.js

To me this seems like a mistake. I only learned two ways to define a function:

var foo = function() {};

or

function foo() {};

The combination of both seems redundant.

Also, it does not seem to work. E.g.

var foo = function bar() {};
foo();  // works.
bar();  // -> Uncaught ReferenceError: bar is not defined

Is there any reason to repeat the function name after the "function" keyword? It seems wrong to me, but I have seen it more than once, so I am wondering.

Answer TLDR

Long answer and more details in the linked QA.

Short answer: The function name does have an effect: - as a local symbol inside the scope of the declared function. - as name property stored on the function itself.

var foo = function bar() {
  console.assert(foo === bar);
}
console.assert('undefined' === typeof bar);
console.assert('bar' === foo.name);
// trigger assert() inside the function.
foo();

// the following might be browser-dependent:
var anon = function () {}
console.assert('anon' === anon.name);
var obj = {method: function () {}};
console.assert('method' === obj.method.name);
obj.method2 = function () {};
console.assert('' === obj.method2.name);
donquixote
  • 4,877
  • 3
  • 31
  • 54

0 Answers0