Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm currently face with a problem where I have two modules that I call that need to be able to modify the same variable.
I decided to create a global variable called global.APP_NAME = {} and store the variables that I need in that.

But I have been reading that it is bad practice to use global variables. Why is it?

I am only creating one variable, that should not collide with anything else because it is the name of my application.

like image 806
C1D Avatar asked Feb 07 '26 04:02

C1D


1 Answers

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. When all variables are either local or passed to a function, you can be sure that the side-effects of the function are limited.
  • Global variables work at a distance. Screwing with the value of a global could have unexpected effects in a completely different part of the application. When you debug an error caused by that, you will have a very hard time finding out where the variable was changed to a wrong value.
  • Global variables share a namespace, so you can inadvertently reuse them although you don't intend to do so.
  • It's hard to tell how important a global variable is. You never know if it's used by just two functions or if its value is important all over the place.
  • ...and many more reasons...

When you have two modules which share data, you should create an object with that data and explicitly pass it to each function which needs it (and only those which actually do).

like image 125
Philipp Avatar answered Feb 12 '26 04:02

Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!