Hacker News new | past | comments | ask | show | jobs | submit login

I'm not sure about this. The very first link I clicked had some iffy advice.

The "Function declaration" section makes an unsubstantiated claim that function declarations are an antipattern, neglecting to mention the significant difference in effect between a declaration and a function expression assigned to a variable. Declarations are subject to function hoisting; IIFEs and expressions assigned to variables aren't. (But the variables themselves are, which is further confusing.) In other words:

  fnDeclaration(); // This function is ready for use.
  function fnDeclaration() {
    console.log('This function is ready for use.');
  }

  // - but -

  fnExpression(); // TypeError: undefined is not a function.
  typeof fnExpression; // 'undefined'
  var fnExpression = function() {
    console.log('This function is ready for use.');
  };

  fnExpression(); // This function is ready for use.
  typeof fnExpression; // 'function'
Named function expressions are neat, I guess, but the trailing F looks more like an odd, Hungarian stylistic choice than a fix for a serious issue in IE<8. Given that the author(s) either didn't know or just forgot to mention (at first) the IE problems you could meet with if you followed this advice, I'm a little bit concerned about this reference.



Personally, I prefer function declaration for most functions (unless they are bound dynamically). The reason is very simple: the "function" keyword at the beginning of the line makes it very clear and obvious what's going on. I prefer the code to be its own documentation.


Also, aside from hoisting, there is a much better solution for named+assigned function declarations, because the reason for naming such a function is to use it recursively. Hence, just use the verb form of the word "recurse" and it immediately self-documents that the function is recursive:

    var fibs = function recurse(n, curr, last) {
        curr = curr || 1;
        last = last || 0;
        return n <= 0 ? last : recurse(n - 1, curr + last, curr);
    };


Good luck with your stack traces.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: