0

I'm working in modules with webpack and in order to avoid creating variables in the global scope, I did this Revealing Module Pattern:

function establishArrays() {

    let globalVar = (function () {
        let projectList = [];
        return {
            projectList: projectList
        };
    }());
};

export default establishArrays;

If I put console.log(globalVar.projectList) in the function, it works when run, showing []

Now establishArrays is part of a file index.js into which is imported renderProject as well. However, when I do this,

function renderProject() {
  console.log(globalVar.projectList)
}

I get this error, Uncaught ReferenceError: globalVar is not defined at main.js:2

What could be causing this? In index.js I have imported and run them:

import createUUID from './UUID';
import establishArrays from './establishArrays';
import createProjectListeners from './createProjectListeners';
import renderProject from './renderProject';
createUUID();
establishArrays();
createProjectListeners();
renderProject();

Thanks!

acchang
  • 59
  • 7
  • `function establishArrays() { let globalVar =` means that `globalVar` is only scoped to inside the function, it's not global – CertainPerformance Mar 11 '21 at 03:35
  • @CertainPerformance Thanks for weighing in. Is there a way to make this scoped globally? I was following this which suggested I might be able to https://medium.com/@petertumulty/avoiding-the-global-scope-with-the-revealing-module-pattern-6796ae7af1b9 – acchang Mar 11 '21 at 16:07
  • There's no good way. The whole point of using JS modules and Webpack is to **avoid global variables**. Programs are much easier to understand and maintain when the dependency chain is explicitly established by `import` chains. While you *could* assign to the global object `window.globalVar = something`, that's a pretty bad idea that should be reserved only for the rarest of cases, like when a big library like jQuery has finished constructing itself and exposes *one* variable globally to allow for others to interact with it. – CertainPerformance Mar 11 '21 at 17:45
  • Got it, thanks @CertainPerformance I was trying to avoid having to write it all in modules, but it's helpful to have someone more experienced confirm this for me. I haven't gotten to jQuery in my studies yet, but what you say makes sense. – acchang Mar 11 '21 at 19:08

0 Answers0