2

Probably not the best question ever, but I have a doubt here.

Is there any difference writing this:

var myFunction = function myFunction () {};
myFunction.instance = null;

and this:

var myFunction = function () {};
myFunction.instance = null;

edit: read carefully please , this is not a duplicate of this var functionName = function() {} vs function functionName() {} The link above is explaining hoisting, here this is about assignement of two hoisted function, one anonymous, one not.

Community
  • 1
  • 1
François Richard
  • 6,111
  • 10
  • 34
  • 66

2 Answers2

5

No. There is no difference1.

In both case a new function object is created (through a Function Expression), assigned to a variable, and then mutated through a property assignment.

The only difference is one function has a name assigned, which may prove useful: see myFunction.name, myFunction.toString(), or access to myFunction from within the function scope. Since it was a Function Expression (as opposed to a Function Declaration) the name has no bearing on variables in the defining scope; 1caveats for legacy browsers are covered elsewhere.

user2864740
  • 54,112
  • 10
  • 112
  • 187
  • You're mostly correct, but saying "No. There is no difference" and then "The only difference" is a bit weird. The differences are (1) having named functions is great for debugging, but (2) they can can cause errors in older browsers. The second of those is pretty important (ex: http://stackoverflow.com/a/8548848/2407870). – Chris Middleton Dec 21 '15 at 04:32
  • Yeah, it's not relevant for most things, but OP didn't really specify \*what\* differences he cared about, so it could be relevant. – Chris Middleton Dec 21 '15 at 04:33
  • this was very clear , don't waste time on such things really =D thank you – François Richard Dec 21 '15 at 04:33
1

Not really.

The main difference would be the size of your code (one statement being longer) since storing a function into a variable ignores the actual function name:

var a = function b() {};
console.log(b); // Uncaught ReferenceError: b is not defined(…)

The reason it appears the same in your case is that you are using the same variable name for both and thus your variable will point to the function.

The other difference would be the values returned from myFunction.toString() and myFunction.name, as pointed out by user2864740

var a = function b() {};
console.log(a.toString()); // "function b() {}"
var c = function() {};
console.log(c.toString()); // "function () {}"
nem035
  • 31,501
  • 5
  • 73
  • 88