12

Given this Javascript example I found

var sum = function() {
  var i, sum = 0;
  for(i = 0; i < arguments.length; i += 1) {
    sum += arguments[i];
  }
  return sum;
};

What advantage is there in assigning a function to a var?

2
  • Your example seems to be intentionally contrived to explain the scope difference between the outer sum (function) and inner sum (integer). Contrived examples rarely make real world sense, they tend to exist purely to showcase a point.
    – Flater
    Jun 11, 2020 at 11:42

5 Answers 5

9

The short answer I believe is simply that you are creating an anonymous function assigned to a variable, as opposed to creating a named function with...

    function sum() {}

A good way to check the differences is to call .ToString() on them and see the difference or you could do console.log(sum.name). One will give an actual name and the other nothing, namely the anonymous function (the one assigned to the var). There are specifics too, like the var sum = function(){} gets defined at run time and the function sum(){} gets defined at parse time.

4
  • What I mean by the last sentence is that if you tried to call sum() in a previous line above where it was defined by var, then there would be an error. If it is defined like in my answer then there would be no error, even if the call was above the function. Sep 22, 2012 at 23:55
  • 15
    That explains the difference, but I don't think it explains the advantage. Sep 23, 2012 at 0:39
  • what's the difference between parse time and runtime? Sep 23, 2012 at 12:52
  • 2
    Doesn't have anything to do with named functions, you can still assign a named function to a variable Apr 10, 2013 at 17:48
5

One advantage is that you can't use a function declaration in a block. They can only be at the top level of a file or directly within another function.

if (true) {
  function foo() {}
}
try {
  function foo(){}
}
switch (true) {
  default:
    function foo(){}
}

These are all unspecified by the standard and browsers do different things, see https://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements. So if you have to use the other style sometimes, for consistency you might want to do so always

Also, I'm not sure of this one but if I remember correctly some old minifiers weren't smart enough to to handle function declarations and don't rename them.

3

I'm not a Javascript expert, so take this with a grain of salt. I think in some cases people might do it for style and same thing could be achieved by simply writing "function sum() {...}"

However, assigning a function to a variable is a very powerful technique in functional programming. If you are familiar with OOP, it is somewhat similar to polymorphism. Think of the classic example of Animal base class and Cat/Dog deriving classes. You can write code that works with Animal but when it calls a function, that function could do different work depending on the type of an instance.

In functional programming, you could have an algorithm which works with "a function" but if you are using a variable to call that function, you have the flexibility of assigning a different function at runtime.

For example, let's say you write an algorithm to present 10,000 data points in a window which is only 500 pixels across. Each pixel will then represent 20 data points and in order to present them you need to aggregate those 20 data points into a single value.

So let's say you define an algorithm to present the 10,000 points and this algorithm uses a function variable called aggregate like so:

...
displayValue = aggregate( numbersInOnePixel );
...

Now at runtime your user can select how the data is to be aggregated. Your actual function variable can be any one of the following:

aggregate = function sum() {...}
aggregate = function min() {...}
aggregate = function max() {...}
aggregate = function average() {...}
0

Its mostly a matter of style, since the only situations where the difference shows up (calling some of the functions before ending all declarations; using the toString method) are kind of corner cases, in my oppinion.

One of the arguments I have heard supporting this var = style is that it is consistent with how you declare normal variables. This limits the number of language features you use and makes it simpler to indroduce your program to someone new to Javascript.

0

I'm not an expert at all about this but, a scenario in which I think this is useful, is when you have to work with a laaaarge imported package, whether because in your work-team have created this package along the "years" or because the package was meant to be like this, you might find yourself using a lot of times in your new-job-just-inherited-3000-lines-long script, many functions from many different subpackages, and here is when this "feature" comes into your rescue.

You could be having to write many many times some things like:

masterMath.statistics.countrySizer.marketPredictor(arg1, arg2)

or you could just:

mp = masterMath.statistics.countrySizer.marketPredictor

and then:

mp(arg1, arg2)

now, imagine the same with a bunch of different subpackages from masterMath.statistics and masterMath and masterMath.secretOfTheWorld etc, etc, you get the point, and believe me, it happens.

I know this is not the only way of doing so, but it is a way.

Note: appropriated naming is out of the scope of this answer.

Not the answer you're looking for? Browse other questions tagged or ask your own question.