
“var functionName” vs “function functionName” - baptou12
http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname
======
yiransheng
An example case where "var" method is useful:

    
    
        function make_dot_product(dim) {
    
          if (dim === 3) {
             var dot = function(a,b) {
                return a.x*b.x+a.y*b.y+a.z*b.z
             }
          } else if (dim === 2) {
             var dot = function(a,b) {
                return a.x*b.x+a.y*b.y
             }
          }
      
          return dot
        }
    

vs.

    
    
        function make_dot_product(dim) {
    
          if (dim === 3) {
             function dot(a,b) {
                return a.x*b.x+a.y*b.y+a.z*b.z
             }
          } else if (dim === 2) {
             function dot(a,b) {
                return a.x*b.x+a.y*b.y
             }
          }
      
          return dot
        }
    

The second case is erroneous, as it will always return 2-dimensional dot
function (even if you call make_dot_product(20)). The is because function
nameSpace() is defined at parse time, so inside the make_dot_product scope,
two instance of dot functions are created, with the second overwriting the
first. If we use var f = function() {...} this can be avoided.

~~~
jonahx
Not a great counterexample imo:

    
    
        function make_dot_product(dim) {
    
             return (dim === 3) ? dot3 : dot2;
    
             function dot3(a,b) {
                return a.x*b.x+a.y*b.y+a.z*b.z
             }
    
             function dot2(a,b) {
                return a.x*b.x+a.y*b.y
             }
    
        }

~~~
Cthulhu_
I think I prefer this one, although I'd put the return at the bottom for
convention's sake. A lot of people don't know - or want or need to know -
about the specifics of hoisting and what-have-you, and will consider this
counter-intuitive.

------
scarmig
An additional wrinkle: recursive functions. If you've got a recursive
function, you absolutely must use a function declaration to introduce the
function identifier. Otherwise you inadvertently create a closure. Consider:

    
    
      var a = function(b) {
        if (b === 0) {
          return true;
        }
        return a(--b);
      };
      var b = a;
      a = function() { return false; };
      b(5);
    

As an alternative, you should go

    
    
      var a = function a2(b) {
        if (b === 0) {
          return true;
        }
        return a2(--b);
      };
      var b = a;
      a = function() { return false; };
      var a2 = function() { return false; };
      b(5);
    

Perhaps counterintuitively, a2 doesn't leak into the containing scope, which
makes it safe to use within the function it declares.

Some older browsers fuck this up though, IIRC.

~~~
yawboakye
you can use the same name for both the variable and the function in your
(alternative) solution. It's better and less confusing. and another reason
your alternative is preferred is because arguments.callee is going away (if it
isn't gone already) :/

~~~
scarmig
Indeed. Having separate names was for didactic purposes. In real code, naming
the variable the same as the function would be very strongly recommended.

------
AdrianRossouw
i know it's sort of side effect driven, but i like function hoisting.

it's one of my main tools to fight the callback pyramid of doom.

use named functions, place them below the code that uses them.

all flat.

~~~
wakaflaka
You are just asking for race condition issues with that type of "solution."

~~~
Jare
Are you referring to a case like this?

    
    
        {
          f();
          var a = 3;
          function f() {
            console.log(a);
          }
        }
    

That will print "undefined" because the entire function f() is hoisted and
callable in the first line, but the variable a has not yet been assigned the
value. That's not a race condition (those are related to timing in concurrent
systems) but is certainly the sort of counter-intuitive visibility that makes
me prefer to use function expressions most of the time.

------
mattmanser
I honestly don't understand people who regularly use variables to declare
functions (with the exceptions of the _extremely_ rare cases it might be
useful).

My POV is you simply shouldn't be putting a function in a variable, it's
supposed to be reusable code and you've just made it's position a completely
pointless dependency as well as obfuscated the code's meaning.

A named function is clearly supposedly immutable, reusable code (save monkey
patching). A function in a variable looks like you might change it.

I want to stress, there are very good reasons to assign a function to a
variable. There are also very good reasons to declare a function within the
scope of another too. But they are few and far between.

To willy nilly declare functions like they're variables. Bizarre. Perhaps
someone who does it can explain what it gains them? The place I first saw it
was in Crockford's the Good Parts, but he seems to have stopped doing it when
you go look at his code.

~~~
windsurfer
Have you ever worked in a large Javascript codebase? Anonymous functions allow
for namespacing. Declare your namespace as var Namespace = {}, and then attach
functions as Namespace.foo = function(){}. Typically in a definition file I
will have var self = Namespace; and then declare functions as self.foo =
function(){}.

~~~
Roboprog
I'm rather fond of that style, or the variant:

    
    
        projectname = {
            A_CONSTANT: ...,
    
            someFunc: function(...) {
            },
    
            ...
    
            lastFunc: function(...) {
            }
        }
    

Basically, JSON layout but with the functions in the resulting namespace.

Debugging & diagnostics for this layout in Firefox and Chrome is not a
problem. As for IE, well, some things can't be fixed, I guess.

~~~
sopooneo
I do that a bit, but found it tricky to end everything with a comma, and
effectively use ":" instead of "=" for declarations. Lately I've been doing

    
    
        projectname = (function(){
            self = {};
    
            self.A_CONSTANT = ...;
    
            self.someFunc = function(...){
            };
    
            self.lastFunc = function(...){
            };
    
            return self;
        })();
    

I _think_ that produces the exact same end result, but someone set me straight
if I'm mistaken.

~~~
Roboprog
What you do is a bit more complicated, but has the benefit of making your data
"private" within a closure. You are using a function as an object, and
assigning other functions as fields within its "prototype". I _think_ these
inner functions can call each other w/out a prefix, as methods of the same
object.

My version is the "static method" version that requires the namespace and a
dot before any function calls. I'm OK with that, unless I need a bunch of
instances of something.

P.S. - the semicolons don't really do anything (other than make Doug C feel
good), as JS is a line oriented language, and will complete statements when
they "look done", semis or not. Think of semicolons in JS like colons in
BASIC: they let you put a second statement on the same line.

------
schrodinger
One big difference is that:

    
    
        function functionName()
    

will show up in a stack trace with a name, whereas the other won't.

You can also do this:

    
    
        var f = function functionName() { }

~~~
evilpie
Actually that's not true at least in Firefox and probably chrome.

Take a look at [http://jsfiddle.net/2LsSg/](http://jsfiddle.net/2LsSg/).

    
    
      window.onload/g@http://fiddle.jshell.net/2LsSg/show/:23:5  
      window.onload/f@http://fiddle.jshell.net/2LsSg/show/:26:5  
      @http://fiddle.jshell.net/2LsSg/show/ line 29 > eval:1:1  
      window.onload@http://fiddle.jshell.net/2LsSg/show/:29:1
    

(I guess jsfiddle wraps the JS code in a window.onload handler, which makes
this a bit more ugly)

~~~
randallsquared
It's true in node.js, as of last year, which is where I use the style "var
name = function name(){};", because debugging dozens of anonymous functions in
node.js' callback playground will ruin your day.

~~~
thedufer
Not true as of 0.10.24, which is what I have installed.

------
reconor
Using var to declare a variable later assigned to an anonymous function can
help with managing larger JavaScript projects where scoping and data member
access is important. Here is a pattern I tend to apply rather frequently,
included is an example for a custom instance object, which would be created
with 'new', and a Namespace object:

    
    
        var MyObject;
        (function() {
          var staticPrivateVariable;
    
          MyObject = function(opts) {
            // Do Initialization Stuff
          };
    
          MyObject.prototype.publicInstanceFunction = function(opts) {
            // Do instance stuff
          };
        })();
    
        
        var Namespace;
        (function() {
          var staticPrivateVariable;
    
          Namespace = function(opts) {
            // Do Initialization Stuff
          };
          Namespace.publicFunction = function(opts) {
    
          };
    
          function privateFunction(opts) { 
            // Do some private stuff
          }
        })();

------
lotides
I've been trying to learn to code (I'm a designer) for a while now. I've read
books, played around with making things and I'm now taking the JavaScript
course on Codecademy. It taught me:

    
    
       var functionName = function() {
       // whatever
       }
    

I had no idea there were other ways to write a function. I still don't
understand what the benefits or drawbacks are of each method. Maybe I haven't
made it that far yet. But I literally have no idea what most of you are
talking about in this thread. I feel like I visited a post written in chinese.

The scope of learning to code seems overwhelming. Finding small bugs in syntax
and design is stressful. What I'm supposed to learn (language, style, syntax,
frameworks) seems to change faster than I can learn it. I wish I would have
started all of this earlier ... like when I was 10.

~~~
gabemart
I am in a similar position to you, in that I only very recently picked up any
javascript.

What's worked for me: use whatever meager skills you have to work on a real
project that you find interesting. Not something that can hurt people if it
goes wrong, but something you care about. Concentrate on the user experience.
Eventually, you'll learn better ways to do things as you need to.

I made [http://asoftmurmur.com](http://asoftmurmur.com)

If you want a laugh, look at the source (the javascript at the bottom of the
main index). It's probably the worst JS I've ever seen, but I concentrated on
the user experience and I'm pretty happy with how that worked out. I'm now
building an Android version and the source is a thousand times more elegant
and concise. In the grand scheme of things, I'm sure it's still awful, but
that's fine, so long as the user experience is good. Next time the code will
be better.

Build something real. When you run into a problem you can't solve by yourself,
ask for help. This will naturally create a narrow but ever-expanding scope in
the face of a limitless quantity of knowledge. I don't know anything about
programming, but that's what's worked for me so far.

~~~
cmbaus
I'm using asoftmurmur now. I think it is the best noise generator out there.
Who cares what the code looks like?

------
grumblestumble
I'm 'ardkore and rigidly enforce `var functionName = function functionName()
{}`, under threat of flaying.

~~~
thedufer
What's the goal there? v8, at least, will give the name in a stack trace even
if the function is declared like `var a = function(){}`.

~~~
Cthulhu_
Really? I'm using Chrome, and at least for me, unfortunately it doesn't.
Second, V8 isn't the only JS engine out there, a lot of tools will simply put
the function as 'anonymous function' in stack traces.

~~~
thedufer
> var a = function(){throw Error('err')} undefined >
> try{a()}catch(err){err.stack} "Error: err at Error (native) at a
> (<anonymous>:2:26) at <anonymous>:2:5 at Object.InjectedScript._evaluateOn
> (<anonymous>:641:39) at Object.InjectedScript._evaluateAndWrap
> (<anonymous>:580:52) at Object.InjectedScript.evaluate (<anonymous>:495:21)"

The "at a" is what we're looking for. I develop largely in Chrome; its been
doing this for months, at least.

It also works in IE11 (the only version I have readily available), Firefox,
and Safari.

------
subbu
Its called function hoisting. Ref: [https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Refe...](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting)

~~~
moron4hire
Also, the latter syntax names the function for the stack frame, which is
useful for debugging. You will sometimes see MyClass.prototype.myFunc =
function myFunc_(){}, because otherwise myFunc is only an anonymous function
assigned to a property on the prototype object.

And the trailing underscore is to placate some version of IE. Or something. I
can't keep it all strait when I'm just out of bed.

~~~
thedufer
That double-naming thing is going out of fashion, since modern browsers +
node.js all know how to figure out function names without it.

------
yawboakye
The primary difference is "hoisting" [https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Refe...](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting). Closure can be
created in both cases.

Also, functions have names.

    
    
         var funcName = function () {};  
         funcName.name; // ""
    
         function func2() {};  
         func2.name; // "func2"  
    

Thus, anynomous functions are truly _anonymous_ whether or not they're
assigned to a variable. `func2` can be assigned to a variable too. It'd retain
its name (`func2`).

------
yiransheng
One pattern I have seen emerging is

    
    
        Object.prototype.method = function Object$method() { ... }
    

an interesting mixture of both method.

------
gopalv
Neither would be any good, really for better coding.

namespace.functionName = function() { }

I'm not talking about performance here, but from a sheer maintainability
nightmare that JS creates. If you care about this, don't let your functions be
unbound.

The only reason to store a function in a var is because it is a closure.

And in a way, a closure is data encapsulation in a totally non OO way.

~~~
Terr_
> namespace.functionName = function() { }

I'd rather use Asychronous Module Definitions:
[http://requirejs.org/docs/whyamd.html](http://requirejs.org/docs/whyamd.html)

------
badman_ting
I recommend named functions, because a stack trace 12 deep of all anonymous
functions is a real bummer.

------
yiedyie
But:

    
    
        functionOne = function() {
        // Some code

};

(i.e. without the var) is represented same as:

    
    
       function functionTwo() {
        // Some code

}

is it?

~~~
LunaSea
No, with or without the var doesn't change the fact that it is still a
variable declaration.

Without the "var" keyword, you just created a global variable rather than one
restricted to your local scope.

~~~
jaredmcateer
The function declaration is still restricted to the scope it's within. The
problem is that the function declaration does some additional hoisting magic
nothing else gets. If you declare a variable in the middle of a function the
variable name gets hoisted but the value does not. If you declare a function
in the middle of another function the name gets hoisted but so does the value.
This can lead to some additional quirkiness, which is why it's recommended to
use the expression assigned ot a variable, to maintain consistency.

~~~
sarink
+99999

------
niix
Also hoisting.

