Why are global variables considered bad practice? (node.js)

I am currently facing a problem when I have two modules that I name that should be able to modify the same variable. I decided to create a global variable with the name global.APP_NAME = {}and save the variables that I need.

But I read that using global variables is bad practice. Why is this?

I create only one variable, which should not interfere with anything else, because this is the name of my application.

+1
source share
2 answers

- , .

  • , , . , , .
  • . . , , , .
  • , , .
  • , . , .
  • ... ...

, , , ( , ).

+11

, , , . , node.js , "app.js", "server.js" - .

- "" ( , APP_NAME.users) . , "app.js" :

var config = {
  myVar: 100
}

, . . :

var module = require('./lib/myModule.js').init(config);

init, . :

var localConfig = null;
exports.init = function(config) {
  // merge the two config objects here
  localConfig.myVar = config.myVar;
}

, . - :

exports.modifyGlobalConfig = function() {
  global.myVar = myLocalValue;
}

app.js .

+2

All Articles