adnanmuttaleb
adnanmuttaleb

Reputation: 3604

How to a define a global constant from inside a function Javascript?

I am building an application composed of a set of modules that get loaded when the application bootstrap:

const MODULES = []

function registerModules(config) {
  return modules.map(module => (new module(config)).install());
}

function bootstrap() {
  MODULES = registerModules({...}); 
}

The above of-course will raise an error. What I want to do is to assign the MODULE constant only when the app start but then it should be fixed. Is this possible?

Initialisation of MODULES has to happen inside bootstrap because of the config variable that I have to pass to registerModules.

Upvotes: 0

Views: 172

Answers (1)

trincot
trincot

Reputation: 350137

If indeed you want to:

  • Have an initialised, but empty MODULES array during the time that bootstrap() is not yet called, and
  • Make MODULES immutable once it has been populated, and
  • Keep the current function signature of registerModules unchanged;

Then you could do it as follows:

function bootstrap() {
    Object.freeze(Object.assign(MODULES, registerModules({...}))); 
    // OR:
    // MODULES.push(...registerModules({...})); 
    // Object.freeze(MODULES);
}

If you don't insist on the existence of MODULES before bootstrap() is called, and you are open to store that information inside an object, then you could proceed as follows:

const globals = {};

function bootstrap() {
  globals.MODULES = registerModules({...});
  Object.freeze(globals.MODULES);
}

Once you are happy with globals, you can also freeze that object:

Object.freeze(globals);

Upvotes: 1

Related Questions