0

What is the difference between using functions from outer-scope (foo and aFunctionFromOuterScope below) and inner-scope (bar and aFunctionFromInnerScope below) in a export default function?

const foo = () => //...

const aFunctionFromOuterScope = () => //...

export default function() {
    const aFunctionFromInnerScope = () {
        foo() // use foo function from outer scope
        bar() // use bar function from inner scope
    });

    const bar = () => //...

    //...

    return {
        aFunctionFromInnerScope ,
        aFunctionFromOuterScope
    };
}

When should I use one or the other?

user2923322
  • 1,072
  • 1
  • 11
  • 25
  • 1
    I don't see what this has to do with modules or exports. It's the same difference as for any other function. – Bergi Nov 26 '19 at 02:56
  • @Bergi sorry, you are right. I guess there would be no reason to have a function out of the scope of this default-exported function (except if I have other exports in the file and want to use the same function)? – user2923322 Nov 26 '19 at 03:02
  • The other reasons to keep them outside (beside the reusability you already mentioned) are clear separation and minor better performance/memory usage, if they don't need access to the scope. – Bergi Nov 26 '19 at 03:04
  • @Bergi can you write an answer why the performance/memory is better, and why fatih's answer is incorrect (i.e. "inner scope functions will be created every time this module is exported"). I will mark your question as accepted. Just a few words are sufficient. – user2923322 Nov 26 '19 at 03:06
  • 1
    @Bergi thank you for cleaning this question and marking as a duplicate. I will thoroughly read the other answers. – user2923322 Nov 26 '19 at 03:13

1 Answers1

1

Functions from the outer scope will be created only once. However, the inner scope functions will be created every time the parent function runs. Inner functions though provide some form of private functions as they are not accessible from outside, and keeps the workspace clean. It depends on your taste and needs.

fatih
  • 1,010
  • 1
  • 8
  • 20