javascriptfunctionexportnested-function

Acces to import of the nested function JS


I need some help to get how some function export works inside JS. Let's say I have this code

function goodbuy() {
    console.log('bye');
}
function myModule() {
    function hello() {
        console.log('Hello');
    }
    hello();
}

export {goodbuy};
export default myModule;

If I call it:

import {goodbuy} from "./main";
import hello from "./main";

goodbuy();
hello();

The output is:

bye Hello

But if I remove hello() call from function myModule() it does not work.

function myModule() {
    function hello() {
        console.log('Hello');
    }
}

with output:

bye

It is a little bit strange for me, as I did not import myModule() where this hello() is called.

PyCharm and VS Code does not show function hello() is not reachable, seems I can export it, but can't use without calling inside the main function myModule().

Could somebody please explain how it works?

I would like an explanation why this function can work with calling inside the main function and can't work without it.


Solution

  • ** return hellow() from myModule** ** And called hellow function like myModule()()**

    function goodbuy() {
    console.log("bye");
    }
    function myModule() {
    return function hello() {
      console.log("Hello");
    };
    }
    
    export { goodbuy };
    export default myModule;
    
      enter code here
    import myModule from "./main";
    import {goodbuy} from "./main";
    
    goodbuy();
    myModule()();