1

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

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

1
  • 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. Commented Aug 7, 2015 at 13:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The article 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.
In that case use expression together with named function like var myFunc = function myFunc() { //...} so you keep benefits of removed hoisting and nice stacktraces.
OP needs to support IE8: "There are also [Named Function Expressions] but I can't use them because there are problems with IE8".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.