1

I'm busy with refactoring of legacy code. Here I can see that for functions used both declarations and expressions. I know that declarations hoisted, expressions are work at time step-by-step execution. There are also NFE but I can't use them because there are problems with IE8. So, my question is:

Can I just replace all function declarations to expressions? Is there any visible or possible problems with such replacement? I want to use expressions, define them at top of the file.

Viacheslav Kondratiuk
  • 8,493
  • 9
  • 49
  • 81
  • 1
    It sounds like you know the differences quite well. As long as you define your function expressions before you call them, you'll be good to go. But if any of the function declarations use recursion you could have issues if your recursive call doesn't match the name of the variable to which it is assigned. – gfullam Aug 07 '15 at 13:13

1 Answers1

0

Why would you want to use expressions? Declarations provide benefit of seeing function name in the produced error stacktrace (Which you will not if you use expression with anonymous function), also you may experience problem with recuriosn if you use expressions.

tomastrajan
  • 1,728
  • 14
  • 28
  • 1
    The article [Function Declarations vs. Function Expressions](https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/) explains why you would choose to use expressions over declarations. Primarily it is for clarity of intent since it promotes tighter code. Crockford also argues in "The Good Parts" that "function statements are subject to hoisting. This relaxes the requirement that functions should be declared before used, which I think leads to sloppiness." I do agree that there is potential for recursive issues in expressions. – gfullam Aug 07 '15 at 13:26
  • In that case use expression together with named function like var myFunc = function myFunc() { //...} so you keep benefits of removed hoisting and nice stacktraces. – tomastrajan Aug 07 '15 at 13:33
  • 1
    OP needs to support IE8: "There are also [Named Function Expressions] but I can't use them because there are problems with IE8". – gfullam Aug 07 '15 at 13:37