DEV Community

Discussion on: Why are global variables bad?

Collapse
 
bgadrian profile image
Adrian B.G.

No pros, but I hope you are referring to the App global level.

There are some "file/module level" (private or public) variables that are ok to be used,for cache/memoization, example you have to build a dictionary and you do not want to do that for every function call (512 keys of something) or consts/enums (like in C or Go).

Most of the time I saw global vars being used is to take shortcuts, to avoid refactoring and the usage of better design patterns (by lack of knowledge or by laziness).

In JavaScript - some things will end up the the global scope (window on browsers), by mistake (forget to put var/const/let), put there by the browser or libraries, but it allows a Module architecture so there shouldn't be any global var specifically set by the developer of the app.

There are some languages that do not have Namespaces/Module scopes so using global variables is not a choice

A number of non-structured languages, such as (early versions of) BASIC, COBOL and Fortran I (1956) only provide global variables. Fortran II (1958) introduced subroutines with local variables, and the COMMON keyword for accessing global variables. Usage of COMMON in FORTAN continued in FORTAN 77,[2] and influenced later languages such as PL/SQL. Named COMMON groups for globals behave somewhat like structured namespaces.[3] Variables are also global by default in FORTH, Lua, Perl, and most shells.

Thread Thread
 
mervinsv profile image
Mervin

Thank you. I think using global vars are too bad for webdev.

Thread Thread
 
bgadrian profile image
Adrian B.G.

The worst thing about them is their Mutability, everyone can change them at anytime, causing spaghetti side effects and there is no way to tell who did what when and why.