I know that global variables are bad.
But if I am using node's module "util" in 40 files in my framework, isn't it better to just declare it as a global variable like:
util = require('util');
in the index.js file instead of writing that line in 40 files?
Cause I often use the same 5-10 modules in each file, that would save a lot of time instead of copy paste all the time.
Isn't DRY good in this case?
Global variables are variables that can be declared with a value, and which can be accessed anywhere in a program. The scope of global variables is not limited to the function scope or any particular JavaScript file. It can be declared at one place and then used in multiple places.
Global variables are considered an anti-pattern in almost any programming language because they make it very hard to follow and debug code. When you browse the code, you never know which function sets or uses a global variable.
Can I have a shared global variable across different files? As we discussed, the global variable is unique to its own module.
A global variable is a variable which is accessible in multiple scopes. In Python, it is better to use a single module to hold all the global variables you want to use and whenever you want to use them, just import this module, and then you can modify that and it will be visible in other modules that do the same.
You could just have a common module.
common.js:
Common = { util: require('util'), fs: require('fs'), path: require('path') }; module.exports = Common;
app.js:
var Common = require('./common.js'); console.log(Common.util.inspect(Common));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With