skip to Main Content

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.

2

Answers


  1. When you do:

    import hello from "./main";
    

    You are importing the default export from the other file, which is myModule, due to this line:

    export default myModule;
    

    You could actually replace that import with any other name:

    import foo from "./main";
    import something from "./main";
    ...
    

    They are all importing the default export from that file.

    This is not the same as importing the hello function defined inside the myModule function. If you want that, you should probably use named exports and write something like this:

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

    The only reason you see Hello in the first case is becase:

    • You import myModule (now aliases as hello).
    • You call myModule (as hello()).
    • myModule internally calls the hello function defined within itself.
    Login or Signup to reply.
  2. ** 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()();
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search