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?

5
  • 1
    I don't see what this has to do with modules or exports. It's the same difference as for any other function. Commented Nov 26, 2019 at 2: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)? Commented Nov 26, 2019 at 3: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. Commented Nov 26, 2019 at 3: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. Commented Nov 26, 2019 at 3:06
  • 1
    @Bergi thank you for cleaning this question and marking as a duplicate. I will thoroughly read the other answers. Commented Nov 26, 2019 at 3:13

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.