2

I recently joined a large software developing project which uses mainly JavaScript and a particular question has been on my mind since day one. I know this issue has been here on SO before, but I have never seen the core question being properly answered. So here I ask it again:

Are there any benefits in JavaScript in using function expressions rather than function declarations?

In other words, is this:

var myFunction = function () {
  // Nice code.
}

in any way better than this:

function myFunction () {
  // Nice code.
}

As I see it, function expressions only introduce negative aspects on several levels to the code base. Here I list a few.

  1. Function expression as the one above, suddenly forces you to be careful with forward references, as the anonymous function object that the myFunction variable refers to, does not exist until the variable expression actually executes. This is never a problem if you use function declarations.

  2. Apart from generating twice as many objects as in the case with function declarations, this usage introduces a very bad programming habit, which is that developers tend to declare their functions only when they feel they need them. The result is code that mixes object declarations, function expressions and logic in something that obscures the core logic of a piece of code.

  3. As a side effect of 2), code becomes much harder to read. If you would use proper function declarations and only var declarations for objects that actually will be variable in the code, it becomes far easier to scan the indentation line of code segment and quickly find the objects and the functions. When everything is declared as "var", you are suddenly forced to read much more carefully to find this piece of information.

  4. As yet another nasty side effect of 2), as users get into the bad habit of only declaring their functions when they feel they need them, function expressions start showing up inside event handlers and loops, effectively creating a new copy of the function object either each time an event handler is called or for each turn in the loop. Needless to say, this is bad! Here is an example to show what I mean:

    var myList = ['A', 'B', 'C'];

    myList.forEach(function (element) {

    // This is the problem I see.
    var myInnerFunction = function () {
        // Code that does something with element.
    };
    

    };

So to sum up, at least in my view, the only situation in which it is fair to use something like:

var myFunction = function () {
  // Nice code.
}

is when your logic intends to change the myFunction reference to point at different functions during execution. In that situation myFunction (the variable) is something that is variable in the code, hence you are properly informing a different programmer of your intents, rather than confusing him/her.

With this background in mind, I ask my question again. Have I missed something central about function expressions (in the context described above) in which they provide any benefit over function declarations?

Kwen
  • 31
  • 3
  • 3
    http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname – Alex Szabo Jan 18 '16 at 08:39
  • http://kangax.github.io/nfe/ & http://stackoverflow.com/questions/23012644/advantages-to-use-function-expression-instead-of-function-declaration – Oxi Jan 18 '16 at 08:50
  • 2
    While the linked pieces are very interesting and explain the difference between them, neither give any real information as to benefits and drawbacks or general guidelines when to use either... I'm also interested in a "best practices" answer rather than an explanation. – Ward D.S. Jan 18 '16 at 08:54
  • 1
    I think it's hard to answer this definitively. There are subtle differences between the two, which may make one more suited than the other for a given situation. However, everything else being equal, there's no real advantage to an expression, and it does have the drawbacks you mention. – deceze Jan 18 '16 at 09:02
  • 1
    Primarily opinion-based? Looking at my current project (200K by now), there's not even a single function declaration, and I haven't crushed into any of "negative aspects" you've listed. – Teemu Jan 18 '16 at 09:03
  • Should be possible to come up with an industry-accepted standard, like how you are supposed to put all `var` statements at the start of the scope (to where the engine will hoist it). Kwen makes, in my limited experience, good points about the nastier aspects of using expressions, but they have their use. Then again maybe we can't and it will forever be a personal preference (comparable to how everyone structures multiple var declarations differently). – Ward D.S. Jan 18 '16 at 10:54
  • @WardD.S. Have you checked this answer? I think it's pretty thorough in explaining the behaviour, and use-cases for both types above. http://stackoverflow.com/a/2672637/1775089 – Alex Szabo Jan 18 '16 at 11:12
  • 1
    Thanks for the comments. I had already visited many of the links that have been proposed in the comments, but those articles only list the differences and not pros/cons. I admit there is an aspect of personal preference in the subject (except for my point 1) which is real), but as I also observed the other listed effects in the project I have now started to work with, I felt the question felt relevant. As with much, it is a question of discipline, and I am quite sure many JS experts still structure their code properly. For newcomers, it appears to lead to the bad habits I listed. Thanks again! – Kwen Jan 18 '16 at 11:53
  • @Kwen #1 is not actually a problem, it's a good practice always to define your variables/functions before using them, and it's not hard at all when you've used to do so. #4 has a partial point, "function expressions start showing up inside event handlers and loops". But, modern JS engines are optimizing code pretty well, hence this actually haven't been a defeat for a long time. – Teemu Jan 18 '16 at 12:23
  • @Teemu: I think you are slightly missing the angle of my question here. Let me rephrase the question. "What is the purpose of declaring something that is constant (the function body) as variable? What do you gain in doing this all over in your code?" Regarding optimization, you are wrong. Try a function expression inside a loop and you will see that you will get as many function objects as the loop goes around. Just because you don't do this in your code, does not mean that newcomers don't appear to easily fall for this mistake. It is to this particular point my question refers to. – Kwen Jan 18 '16 at 13:43
  • @Kwen I never create functions in a loop, I thought you were talking about something like callback function in `forEach`'s arguments etc. – Teemu Jan 18 '16 at 13:46
  • @Teemu: Sorry if I was unclear on that point. =) I have updated point 4) above with sample code so that it becomes more clear the situation I would wish newcomers to avoid. My point has been that I feel that function expressions of this format "invite" less experienced users to commit these mistakes. =( – Kwen Jan 18 '16 at 14:10

0 Answers0