-1

I have been writing functions like

var functionname = function(param)
{
}

rather then

functionname(param)
{
}

does it provide any advantage of the format or any garbage collection happens when i write like the first syntax?

Hacker
  • 7,798
  • 19
  • 84
  • 154
  • in the first one, you are assigning an anonymous function to a variable. in the second you are declaring a named function. they can both be called similarly, so it shouldn't matter – Jesse Oct 01 '15 at 17:12
  • 2
    It's strange to hear such basic questions from a hacker :) – Sergio Tulentsev Oct 01 '15 at 17:22

2 Answers2

1
(function() { "use strict"; f(); function f() { console.log(1); }; })();

1

(function() { "use strict"; f(); var f = function() { console.log(1); }; })();

Object expected

Function expressions var name = function() { ... } are not hoisted, while function decarations function name() {...} are.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • `var name=...` also hoisted, but before assigning it _undefined_ – Grundy Oct 01 '15 at 17:22
  • also for second case: _Uncaught TypeError: f is not a function(…)_. this error in last chrome – Grundy Oct 01 '15 at 17:28
  • @Grundy - Yes, that's exactly why i used the phrase "function expression" and not "function variable" or "variable". This is also why the output is "Object expected" and not "'name' is undefined"; though "Object expected" is a bit ambiguous. – Louis Ricci Oct 01 '15 at 17:29
  • but not clear for me, what you mean _Object expected_, when error is _f not a function_ – Grundy Oct 01 '15 at 17:30
  • @Grundy - the more ambiguous "Object expected" error is reported by IE11. I suspect one browser is following the spec and the other isn't (or the specification is ill defined for tis error). – Louis Ricci Oct 01 '15 at 17:30
  • hm, you right, Edge also get _"Object expected"_. I not sure in what place of specification we can see what error should be :-) – Grundy Oct 01 '15 at 17:32
  • interesting: type exception same: `TypeError` but different message :-) – Grundy Oct 01 '15 at 17:39
0

first of all, u should understand the scope matter for this function.

when u write:

var a = function(){} --> the function is anonymous outside the var a- scope.

it means, that out of this district, the function will not be able to be accessed. another thing is memory usage- here u create a function which takes memory, and a pointer outside the function pointing on it as a soft link.

when u write function a(){} ---> there is a public pointer named a for this function as a hard link.

so, if you want to create a private function- go for it.

i know that it's common to create functions using: function funcName(){);

  • methinks your explanation a bit wrong: one differense in first case _a_ before assigning is _undefined_ in second - _a_ function in all places current scope – Grundy Oct 01 '15 at 17:24